Im now working on a grails project, and Im having a hard time using regex in filtering the desired data i wanted to. this is how it goes, I have a field that can accept all letters and numbers (upper and lower case), and all special characters that is on the keyboard (@*$&#). It will only accept an Input if it is a combination of numbers and letters (0925abc) or a combination of letters, numbers and special characters (0925abc?><). the system will reject the input if it is pure letters (adCbT), pure numbers (0383) or pure special characters (@#$>_+-). Is this possible to do with regex constraints in grails? thanks for sharing your knowledge.
-
Is this w.r.t. the Domain Class fields? Have you tried using a validator? grails.org/doc/latest/ref/Constraints/validator.htmlSagar V– Sagar V2012-05-02 05:36:09 +00:00Commented May 2, 2012 at 5:36
-
yes it is, but i think it would be wasteful in lines if I use a validator for this. I believe that it would be a lot easier to use regex validation, im just confused on how to use it.antibry– antibry2012-05-02 05:46:51 +00:00Commented May 2, 2012 at 5:46
-
The operation by itself is pretty efficient if you intend to do it across all the instances. Also, regex works the same here as anywhere else. Anyway, could you give a code example? It is difficult to solve your issue without seeing any sample code.Sagar V– Sagar V2012-05-02 05:50:04 +00:00Commented May 2, 2012 at 5:50
-
So, what you are looking for is a single regexp which checks your contraints, don't you?rdmueller– rdmueller2012-05-02 08:54:24 +00:00Commented May 2, 2012 at 8:54
Add a comment
|
1 Answer
So, if you are just looking for a regexp which fits your contraints, something like
'.*([a-zA-Z][0-9@*$&#]+|[0-9][a-zA-Z@*$&#]|[@*$&#][0-9a-zA-Z]).*'
should do the trick. It makes sure that there is at least one transition from one character class to another in your input.
with a negative lookahead, it is even a little bit easier to maintain
'^(?![a-zA-Z]+$)(?![0-9]+$)(?![@*$&#]+$).+$'
the three terms make sure that the input does not consist of only charecters from one character class.
here is some code to test the expression:
def ok = ['asdasd90','90asdas','asd#sdfsd9','asd9sdf','908787#@']
def nok = ['asdewSDFDSFasd','23803','@*$&#']
def expression = '^(?![a-zA-Z]+$)(?![0-9]+$)(?![@*$&#]+$).+$'
ok.each { value ->
assert value.matches(expression)
}
nok.each { value ->
assert !value.matches(expression)
}