2

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.

4
  • Is this w.r.t. the Domain Class fields? Have you tried using a validator? grails.org/doc/latest/ref/Constraints/validator.html Commented 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. Commented 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. Commented May 2, 2012 at 5:50
  • So, what you are looking for is a single regexp which checks your contraints, don't you? Commented May 2, 2012 at 8:54

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.