Regular expressions javascript validation

Discussion in 'JavaScript' started by mic_ball, Jul 5, 2012.

  1. #1
    hi

    I have the following JavaScript code that is working:


    <script>
    function validate(form) {
    // Shortcut to save writing
    var pwd = form.elements.lgps.value;
    
    // Check length
    if(8 > pwd.length || pwd.length > 16)
    return false;
    
    // Check for at least 1 lowercase letter
    var rgx = /[a-zA-Z]+/;
    if(!rgx.test(pwd))
    return false;
    
    // Check for at least 1 digit
    rgx = /\d+/;
    if(!rgx.test(pwd))
    return false;
    
    // Check for no spaces
    rgx = /\s/;
    if(rgx.test(pwd))
    return false;
    
    return true;
    }
    </script>
    Code (markup):

    And here's my form:
    
    <form method="post" action="406.php" language="javascript" name="myform" id="myform" onsubmit="return validate(this);">
    
    <input id="lgem" name="lgem" maxlength="20"></div>
    
    <input id="lgps" name="lgps" type="password" maxlength="20" >
    
    <input type="image" value="Entra" id="entraButton" src="entra.jpg" width="81">
    </form>
    
    Code (markup):
    I would like to add a message alert if all the above fails, and also another field in my form to validate. So basically I have a username field and a password field. I want the password field to be between 8 and 20 characters long, and contain at least 1 digit.
     
    mic_ball, Jul 5, 2012 IP
  2. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #2
    // Check for at least 1 lowercase letter
    var rgx = /[a-zA-Z]+/;

    That actually checks for any character that is either lower or upper.
     
    NetStar, Jul 5, 2012 IP
  3. Unni krishnan

    Unni krishnan Peon

    Messages:
    237
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    0
    #3
    You can call the validate method from a wrapper method which throws an alert.
    
    function checkForm(form)  {
        if (!validate(form)) {
            alert("Your password is weak. Please Renter.");
            return false;
       }
        return true;
    }
    
    Code (markup):
    You can then call this method on submit.
     
    Unni krishnan, Jul 5, 2012 IP