Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validator plug-in: validate optional field

Problem I want to validate a field using a custom validator I've created that's essentially a regex for a phone number only IF the field has a value, otherwise it doesn't need to be validated because it's optional.

Custom validator:

   $.validator.addMethod('phone', function (value) {
       return /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
   }, 'Please enter a valid US phone number.');

Rules:

 phone: {
  required: true,
  phone: true
 },
 fax: {
  phone: true
 }

I've even tried:

 phone: {
  required: true,
  phone: true
 },
 fax: {
  required: function(element){
   if (!$("#cf-fax").val()) { return true; } else { return false; }
  }
  phone: true
 }

For reference this is the field I'm trying to reference:

<input type="text" name="fax" class="optional" size="15" maxlength="14" id="cf-fax" />

Any help is appreciated because I am just plain lost. =\

like image 346
creativetim Avatar asked Aug 19 '10 21:08

creativetim


People also ask

What is jQuery validate unobtrusive?

Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. These unobtrusive validation libraries need to be added: jquery.validate.min.js.

Why jQuery validation is not working?

Your answer The "$(...). validate is not a function" jQuery error occurs when the jQuery validation plugin is not loaded or the jQuery-related scripts are loaded in an incorrect order. The validation plugin should be loaded after the jQuery library.

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

How to make a field optional in jQuery?

When you want it as optional field then say "checkName: optional".


1 Answers

You can call .optional() (defined inside the validation plugin) like this

$.validator.addMethod('phone', function (value, element) {
   return this.optional(element) || /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
}, 'Please enter a valid US phone number.');

This is the standard scheme for the validation plugin, take a look at their additional methods here for examples.

like image 94
Nick Craver Avatar answered Nov 08 '22 07:11

Nick Craver