Regular expression is required to add a custom validation method in jquery
I want to do validation of a password field on a login form. The requirement for the password is that the password should be combination of alphabet and numbers. I write a new validation function to fulfil above requirement and added it to jQuery using validator.addmethod()
. The function code is as 开发者_如何学Gofollows
$.validator.addMethod('alphanum', function (value) {
return /^[a-zA-Z 0-9]+$/.test(value);
}, 'Password should be Alphanumeric.');
Problem is this function is not working properly i.e. it accepts alphabetic password (like abcdeSD) and numerical password (like 4255345) and dot give error message for such inputs.
- so is there anything wrong in my code?
- is the written regular expression is wrong and if yes then what will be the correct reg expression?
Use negative lookaheads to disallow what you don't want:
^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z 0-9]+$
Password must contain only alphabets and digits
/^[a-zA-Z0-9]+$/
It must contain alphabet(s)
/[a-zA-Z]+/
It must contain digit(s)
/[0-9]+/
And'ing these
/^[a-zA-Z0-9]+$/.test(value) && /[a-zA-Z]+/.test(value) && /[0-9]+/.test(value)
Use this expression for password for javascript:
/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%_!]).{8,8})/
You can add the any special characters in the expression.
Manually add the characters for in [@#$%_!]
inside.
精彩评论