Regular expressions javascript validation

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>

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>


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.

The way you would do that is to add a variable at the start of the function called isValid and set that to true, then have the different checks set isValid to false. That way you can check at the end of the function if isValid is false, and show your message, before returning the isValid value from the function.

dont forget put type=“text/javascript” at script openning.
^^

That’s not required now. Web browsers accept the script tag as being javascript by default.
It’s only if you are validating against HTML4 and you wish for there to be 0 complaints, that you do that.

Also, when using the <script> tag you should be using it with a src instead of inline content, so it’s the content-type of the file that web browsers use to determine what to use for the script tag.


<script src="script.js"></script>