Monday, February 10, 2014

Custom JQuery Validation Method and Message

Validate forms like you've never validated before! See full documentation here.

List of built-in Validation methods


A set of standard validation methods is provided:

    required – Makes the element required.
    remote – Requests a resource to check the element for validity.
    minlength – Makes the element require a given minimum length.
    maxlength – Makes the element require a given maxmimum length.
    rangelength – Makes the element require a given value range.
    min – Makes the element require a given minimum.
    max – Makes the element require a given maximum.
    range – Makes the element require a given value range.
    email – Makes the element require a valid email
    url – Makes the element require a valid url
    date – Makes the element require a date.
    dateISO – Makes the element require an ISO date.
    number – Makes the element require a decimal number.
    digits – Makes the element require digits only.
    creditcard – Makes the element require a credit card number.
    equalTo – Requires the element to be the same as another one

For example:

<input id="yourEmail" name="yourEmail" class="required email" />
<input id="confirmEmail" name="confirmEmail" equalTo="#yourEmail" />

Now let's implement our custom validation method "naPostal" to validate Canada/US postal code:

<script type="text/javascript">

        jQuery.validator.addMethod("naPostal", function (postal, element) {
            if (this.optional(element)) return true;
            var ctyField = $(element).attr("countryField");
            if (ctyField && $(ctyField).val() == "CA") return postal.match(/[a-zA-Z][0-9][a-zA-Z](-| |)[0-9][a-zA-Z][0-9]/);
            if (ctyField && $(ctyField).val() == "US") return postal.match(/^\d{5}(?:[\s-]\d{4})?$/);
            return postal.match(/^\d{5}-\d{4}$|^\d{5}$|^[a-zA-Z][0-9][a-zA-Z](| )?[0-9][a-zA-Z][0-9]$/gm);
        }, "Invalid postalcode");

        jQuery.extend(jQuery.validator.messages, {
            //Custom error message
            required: "Required field",
            email: "Please enter a valid email address."
        });

</script>

So we can use this method in our HTML code:

<input id="postalCode" name="postalCode" class="required naPostal" countryField="#countryCode" />
<select id="countryCode" name="countryCode">
    <option value="CA">Canada</option>
    <option value="US">USA</option>
</select>