grails validation using matches constraints - regex

8.5k Views Asked by At

Im really having a hard time in matches constraints in grails, im pretty new in it. what i wanted my field to only accept is an input with a format of a phone number, like 02-3546352 where (Area Code)-(Telephone Number). where other characters except numbers and dash are not accepted.Is it possible to filter my input like what i wanted to happen just using regex? please help. thanks for sharing your knowledge.

2

There are 2 best solutions below

1
npinti On BEST ANSWER

Assuming that that is the only pattern you want to match...

Something like this: ^\d{2}-\d{7}$ should match any string which starts (^) with any two digits (\d{2}) follow by a dash (-) and which is then followed by 7 digits (\d{7}) which is finally followed by the end of the string ($).

Take a look at this tutorial for more information.

0
Igor Artamonov On

Yes, it's \d+\-\d+. If you know exact count of mnumbers in area code and telephone, say 2 for area, and 7 for actual numbler, then it will be \d{2}\-\d{7}

Or full example:

static constraints = {
   phone(matches: '\\d{2}\\-\\d{7}')
}