views:

458

answers:

2

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 fulfill above requirement and added it to jquery usding validator.addmethod(). The funtion code is as follows

$.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.

  1. so is there anything wrong in my code?
  2. is the written regular expression is wrong and if yes then what will be the correct reg expression?
+2  A: 

Use negative lookaheads to disallow what you don't want:

^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z 0-9]+$
Mark Byers
Thank You Mark!The regular expression you have given is working perfect man.thank you very much
Param-Ganak
A: 

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)
Anurag