The following JavaScript code returns false if the string contains only numbers or characters other than [a-zA-Z0-9_].
function validate(n) {
return (!/^[\d]+$/.test(n) && /^[\w]+$/.test(n));
}
Is it possible to do this with just a regexp? I want to take a开发者_运维问答dvantage of pattern attributes on the input tag for validation.
<input type="text" pattern="...">
Edit: I also want it to be between 5 and 20 characters
Like this: ^[a-zA-Z0-9_]*[a-zA-Z_]+[a-zA-Z0-9_]*$
This regex matches zero or more characters including numbers, at least one character that isn't a number, followed by another zero or more characters including numbers.
精彩评论