Validation Callback

by davidpauljunior

HTML

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<form id="form-account-details" class="form-register form-validate-password clearfix" method="post" action="/xxxx.html">
    <fieldset>
         <h3>Your Account Details</h3>
        
        <div class="alert alert-error hide">Please enter a valid password</div>
         <h4>Create a password</h4>

        <div id="password-info">
            <ul>
                <li id="length" class="invalid clearfix">At least 8 characters</li>
            </ul>
        </div>
        <div class="control-group password-group">
            <label class="control-label" for="input-password">Password:</label>
            <div class="controls field">
                <input type="password" id="input-password" name="input-password" class="required" placeholder="Password" autocomplete="off" />
            </div>
        </div>
    </fieldset>
    <button type="submit">Submit</button>
</form>

CSS

li.valid {
    color: #56c864;
}

.hide {
    display: none;
}

label.error {
    color: red;
}

.alert-error {
    padding: 5px;
    background: red;
    color: #fff;
}

JavaScript

$(function () {
    var pwdInput = $('.form-validate-password #input-password');
    var pwdValid = false;

    // Function to ensure password conforms to strength requirements
    function validatePwdStrength() {
        var pwdValue = $(this).val();

        if (pwdValue.length > 7) {
            $('#length').removeClass('invalid').addClass('valid');
            pwdValid = true;
        } else {
            $('#length').removeClass('valid').addClass('invalid');
            pwdValid = false;
        }

        // There are many rules here there are ommitted about uppercase, numbers etc.
    }

    // Function to check that pwdValid is true, and if so submit the form, otherwise don't.
    function validatePwdValid(form, event) {
        if (pwdValid == true) {
            form.submit();
        } else {
            event.preventDefault();
            $('.form-validate-password .alert-error').removeClass('hide');
        }
    }

    // When the user enters the password, run validatePwdStrength
    pwdInput.bind('change keyup input', validatePwdStrength);

    $(".form-validate-password").validate({
        submitHandler: function (form, event) {
            //this runs when the form validated successfully
            validatePwdValid(form, event);
        }
    });
});