jQuery Validation Plugin, phoneUS field is breaking form

I've been working on a simple form using the jquery validation plugin for browser-side validating, and for some reason unbeknownst to me it seems like the 'phoneUS' rule seems to be breaking the rest of the validation code.

So long as that field ("tel") is blank on the form, the validation works as intended. But if anything is entered into the telephone field (including letters), then the validation is skipped and the form is submitted, even if other required fields are left blank. However, if the 'phoneUS' rule is taken out of the code, other validation rules applied to the 'tel' input still apply. Needless to say, I'm thoroughly confused.

The script is:

<script type="text/javascript"> $(document).ready(function(){ $('#survey1').validate({ rules: { firstname: { required: true, }, lastname: { required: true }, address1: { required: true }, city: { required: true }, state: { required: true }, zip: { required: true, digits: true }, tel: { required: true, phoneUS: true }, email: { email: true } } }); }); </script> 

the labels and input fields are just simple text boxes with names matching the script. The form action is set to use a php file to email the results to a static e-mail address. If any other information would be helpful, I'll provide it.

I'm relatively new to jQuery, so feel free to offer pointers (superfluous characters, etc.).

Thanks!

1

2 Answers

jQuery Validate does not come with the phoneUS function standard; you have to add it. Before your $('#survey1').validate() code, call this function:

// Add US Phone Validation jQuery.validator.addMethod('phoneUS', function(phone_number, element) { phone_number = phone_number.replace(/\s+/g, ''); return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, 'Please enter a valid phone number.'); 
2

You need to include the additional-methods.js file which contains the phoneUS rule/method.

Alternatively, if you'd rather not include an another JavaScript file, you can manually add just the phoneUS rule/method:

jQuery.validator.addMethod("phoneUS", function(phone_number, element) { phone_number = phone_number.replace(/\s+/g, ""); return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, "Please specify a valid phone number"); 

DEMO:

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like