Pocket
Pocket

Reputation:

JQuery and the validate plugin

Rather than write my own validation I thought i would use JQuery instead however i'm not finding this easy either. I have a few questions which I hope someone can answer. Firstly, the error messages are only appearing when I click submit. How can I get them to appear after exiting each field? Here's my code for validation.

Code:

$(document).ready(function(){
    $("#orderForm").validate({
        rules: {
            shipFirstName: {
                required: true,
            },
            shipFamilyName: {
                required: true,
            },
            shipPhoneNumber: {
                required: true,
            },
            shipStreetName: {
                required: true,
            },
            shipCity: {
                required: true,
            },
            billEmailAddress: {
                required: true,
            },
            billPhoneNumber: {
                required: true,
            },
            billCardNumber: {
                required: true,
            },
            billCardType: {
                required: true,
            },
        }, //end of rules
    }); // end of validate
    }); //end of function

This is my HTML code for the form. I won't show the styling but I have changed it to display a red font.

Code:

<form id="orderForm" method="post" action="x">
      <table id="formTable" cellpadding="5">
        <tr>
          <td>
            <h3>Shipping and Billing Information</h3>
          </td>
          <td>&nbsp;</td>
        </tr>
        <tr>
          <td><label for="shipFirstname">First Name</label></td>
          <td><input id="shipFirstName" type="text" name="shipFirstName" maxlength=
          "30" /></td>
        </tr>
        <tr>
          <td><label for="shipFamilyName">Surname</label></td>
          <td><input id="shipFamilyName" type="text" name="shipFamilyName" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="shipPhoneNumber">Contact Telephone Number</label></td>
          <td><input id="shipPhoneNumber" type="text" name="shipPhoneNumber" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="shipStreetName">Street Name</label></td>
          <td><input id="shipStreetName" type="text" name="shipStreetName" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="shipCity">City</label></td>
          <td><input id="shipCity" type="text" name="shipCity" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="shipPostalCode">Postal Code</label></td>
          <td><input id="shipPostalCode" type="text" name="shipPostalCode" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="billEmailAddress">Email address</label></td>
          <td><input id="billEmailAddress" type="text" name="billEmailAddress" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="billPhoneNumber">Contact Telephone Number</label></td>
          <td><input id="billPhoneNumber" type="text" name="billPhoneNumber" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="fidelityCardNumber">Fidelity card</label></td>
          <td><input id="fidelityCardNumber" type="text" name="fidelityCardNumber" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="billCardNumber">Credit Card Number</label></td>
          <td><input id="billCardNumber" type="text" name="billCardNumber" maxlength="30" /></td>
        </tr>
        <tr>
          <td><label for="billCardType">Credit Card Type</label></td>
          <td><select id="billCardType" name="billCardType">
            <option value="...">
              Choose your card...
            </option>
            <option value="visa">
              Visa
            </option>
            <option value="mastercard">
              Mastercard
            </option>
          </select></td>
        </tr>
        <tr>
          <td><label for="instructions">Instructions</label></td>
          <td>
          <textarea id="instructions" name="instructions" rows="8" cols="30">
Enter your requirements here or comments.
</textarea></td>
        </tr>
        <tr>
          <td colspan="2"><input id="submit" type="submit" name="Submit" value="Submit" </td>
        </tr>
      </table>
    </form>

I also want to use regexs for the postcode and fidelity card. How do I incorporate these into the script? Is this right? Where do I put it?

$.validator.addMethod('shipPostalCode', function (value) {
    return /^[A-Z]{2}\d{1,2}\s\d{1,2}[A-Z]{2}$/.test(value);
    }, 'Please enter a valid Postal Code');
    $.validator.addMethod('fidelityCardNumber', function (value) {
    return /^[A-Z]{1}([A-Z]|\d){4}\s?([A-Z]|\d){5}\s?([A-Z]|\d){3}\d{1}(\!|\&|\@|\?){1}$/.test(value);
    }, 'Please enter a valid card number');

One final thing. Can this script be put in an external js file easily? I am trying to get as much out of the html file as possible.

Thanks

Upvotes: 3

Views: 4546

Answers (6)

jdforsythe
jdforsythe

Reputation: 1067

jQuery.validator.addMethod("stateUS", function(value, element) {
    return this.optional(element) ||
    /^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/.test(value);
}, "The specified US State is invalid");`

For validating two letter abbreviations for US states and DC.

Wanted to comment on the above, but not enough rep - Salty's answer says to use

onfocusout: true

However, according to the docs (and trying it) that's not a valid setting. http://jqueryvalidation.org/validate

A boolean true is not a valid value.

If you're setting truthiness to that value, you need to set a callback function which gets two arguments, element and event - just like Alistair's answer.

Upvotes: 0

Alistair
Alistair

Reputation: 1979

$('#myform').validate({ onfocusout: function(element) { $(element).valid(); } }; 

This will also work.

Upvotes: 0

Salty
Salty

Reputation: 6688

$(document).ready(function(){ $("#orderForm").validate({ onfocusout: true, rules: { shipFirstName: { required: true, }, shipFamilyName: { required: true, }, shipPhoneNumber: { required: true, }, shipStreetName: { required: true, }, shipCity: { required: true, }, billEmailAddress: { required: true, }, billPhoneNumber: { required: true, }, billCardNumber: { required: true, }, billCardType: { required: true, }, }, //end of rules }); // end of validate }); //end of function

That'll make it so that every time you leave a field, it validates it automatically. :)

Upvotes: 2

SolutionYogi
SolutionYogi

Reputation: 32223

By using 'addMethod' call, you are actually adding a 'type' of validation which could be used in your main 'validate' method call.

$.validator.addMethod('postalCode', 
    function (value, element) 
    {
          return this.optional(element) || /^[A-Z]{2}\d{1,2}\s\d{1,2}[A-Z]{2}$/.test(value);
    }, 'Please enter a valid Postal Code');


$.validator.addMethod('creditCardNumber', 
    function(value, element) 
    {
        return this.optional(element) || /^[A-Z]{1}([A-Z]|\d){4}\s?([A-Z]|\d){5}\s?([A-Z]|\d){3}\d{1}(\!|\&|\@|\?){1}$/.test(value);
    }, 'Please enter a valid card number');

Put this code in the same JS file where you have other validation code.

Then, modify your validate method call to:

$(document).ready(function(){
    $("#orderForm").validate({

        rules: {

                    //Your other rules

                    shipPostalCode: { postalCode: true },
                    fidelityCardNumber : { creditCardNumber : true }

                }

    })
   }
 );

Upvotes: 1

Justin Johnson
Justin Johnson

Reputation: 31300

As far as adding your own validation method, check out http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

You might also want to explore using this method instead:

jQuery.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

from the example at http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#rules

Lastely, http://docs.jquery.com/Plugins/Validation indicates that you could also validate like this

which would be cleaner and less JS for you to write.

Upvotes: 1

Daniel Moura
Daniel Moura

Reputation: 7966

This should work, but you first have to fill something in the form. Try writing something in the First name, then delete it and change focus.

Upvotes: 1

Related Questions