Sunday, May 26, 2013

JAVASCRIPT REGEX FOR NUMERIC, NUMBER AND SPECIAL SYMBOL

People often ask for a javascript regex for validating input. normal regex are available but if anyone is interested in a regex expression for valiating input that should contain alpha-numerics and special character then below is the code for validating this type of input.

/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])(?=.*\W).*$/;

This regex can be divided into several parts
the first part (?=.{8,}) tells the minimum length should be 8. You can change it by replacing 8.
the second part (?=.*\d) tells that there must be a number 
the third part (?=.*[a-zA-Z]) tells that allowed alphabets are a-z and A-Z and it is a must
the fourth part (?=.*\W) tells that there should be at least a symbol

Now if you want to impose that password should contain alphabets, numeric  special character and at least one capital alphabet the it should be slightly changed to become
/^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\W).*$/;



Below is illustrated code with HTML to show how the expression will work.

<script language="javascript">
function validate()
   {
    var pattern = /^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])(?=.*\W).*$/;
    if (!pattern .test(document.getElementById("password").value))
    {
        alert("Password should be a cobination of alpha-numerics and a special          symbol with at least 8 characters")
    }
    else
     {
         alert("Validated");
     }
}
</script>
<input type="text" name="password" id="password" value="" />
<input type="button" value="Submit" onclick="validate()" />