regex validation - grails constraints

2.4k Views Asked by At

I'm pretty new on grails, I'm having a problem in matches validation using regex. What I wanted to happen is my field can accept a combination of alphanumeric and specific special characters like period (.), comma (,) and dash (-), it may accept numbers (099) or letters only (alpha) , but it won't accept input that only has special characters (".-,"). Is it possible to filter this kind of input using regex? please help. Thank you for sharing your knowledge.

2

There are 2 best solutions below

3
Flo On BEST ANSWER
^[0-9a-zA-Z,.-]*?[0-9a-zA-Z]+?[0-9a-zA-Z,.-]*$

meaning:
  /
  ^          beginning of the string
  [...]*?    0 or more characters from this class (lazy matching)
  [...]+?    1 or more characters from this class (lazy matching)
  [...]*     0 or more characters from this class
  $          end of the string
  /
1
chm On

I think you could match that with a regular expression like this:

".*[0-9a-zA-Z.,-]+.*"

That means:

"." Begin with any character

"*" Have zero or more of these characters

"[0-9a-zA-Z.,-]" Have characters in the range 0-9, a-z, etc, or . or , or -

"+" Have one or more of this kind of character (so it's mandatory to have one in this set)

"." End with any character

"*" Have zero or more of these characters

This is working ok for me, hope it helps!