Does anyone know a PURE JSP way of doing Alphanumeric validation on a text input?
Use regegular expressions, for example:
String str = "somestring";
if(str.matches("[a-zA-Z0-9]")) {
// do something here if it matches.
} else {
// doesn't match do something else.
}
I can’t get it to return true, am I missing something?
Edit: I forgot that I had to search from the start to the end of the string.
How do you search from the start to the end of the string? Adding a asterisk after the regexp?
Like that:
if(str.matches(“[a-zA-Z0-9]*”))
What if I want only number? Can I do something like:
if(!str.matches(“[0-9]”))
Thanks
Sorry for the late reply but I have been busy.
To match the start of a string, start the pattern with a ^ character. If you want to match at the end, conclude the pattern with a $ character.
I use this link as a reference when I’m about to create regexp’s: http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/index.html
Even though it’s a Javascript article, I find it useful. I’m sure you will find Java-related articles with examples if you search a little.
What snaily posted will only match a single character. Add * to it to match multiple, but unless you want to match an empty string, use + instead
[a-zA-Z0-9]+