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.
Asked
Active
Viewed 5,938 times
2
-
AFAIK you can't do that with only one regex. – m0skit0 Feb 24 '12 at 09:50
2 Answers
3
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

Matt N
- 1,086
- 2
- 9
- 21
1
I don't know if grails supports lookaround, but if it does, this regex will work for you:
/(?=^[\pL\pN!:;]+$)(?!^[!:;]+$)/
explanation:
/ : regex delimiter
(?= : begin positive lookahead
^ : start of string
[\pL\pN!:;]+ : a letter, a digit or a special char one or more times
$ : end of string
) : end of lookahead
(?! : begin negative lookahead
^ : start of string
[!:;]+ : a special char one or more times
$ : end of string
) : end of lookahead
/ : regex delimiter

Toto
- 89,455
- 62
- 89
- 125