Search code examples
regexgrailsgroovygrails-constraints

regex validation - grails


im pretty new in grails.. im having a little problem right now on validation using matches. What I wanted to happen is that a field can accept combination of alphanumeric and special characters, letters only and numbers only, and if the user inputs special characters only, the system should prompt the user an error. i used matches constraints to validate the data, and im having a hard time how could i set the regex where the field will not accept an input with special characters only. please help me.. thanks a lot for sharing your knowledge.


Solution

  • I think I understand your problem, but correct me if I'm wrong. The input is valid as long as there is at least 1 letter or number, right? In other words, if there isn't a letter or number (only special characters), then the input is invalid?

    See if this works:

    /^.*[A-Za-z0-9].*$/
    

    Here is my little groovy test:

    import java.util.regex.Matcher
    import java.util.regex.Pattern
    
    def pattern = ~/^.*[A-Za-z0-9].*$/
    
    assert pattern.matcher("abc").matches()
    assert pattern.matcher("ABC").matches()
    assert pattern.matcher("abc123").matches()
    assert pattern.matcher("123").matches()
    assert pattern.matcher("abc!").matches()
    assert pattern.matcher("!abc").matches()
    assert pattern.matcher("1!bc").matches()
    assert pattern.matcher("!.~").matches() == false
    

    Explained:

    /             regex start
    ^             start of string
    .*            any character (0 or more times)
    [A-Za-z0-9]   at least 1 letter or number
    .*            any character (0 or more times)
    $             end of string
    /             regex end