EzDevInfo.com

jquery-validate interview questions

Top jquery-validate frequently asked interview questions

jQuery validation: change default error message

Is there a simple way to change the default error values in the jQuery validation plugin?

I just want to rewrite the error messages to be more personal to my app--I have a lot of fields, so I don't want to set the message individually for field x...I know I can do that!


Source: (StackOverflow)

jquery validate check at least one checkbox

I have something like this:

<form>
<input name='roles' type='checkbox' value='1' />
<input name='roles' type='checkbox' value='2' />
<input name='roles' type='checkbox' value='3' />
<input name='roles' type='checkbox' value='4' />
<input name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
<form>

I would like to validate that at least one checkbox (roles) should be checked, is it possible with jquery.validate ?


Source: (StackOverflow)

Advertisements

Knockout + mvc 3 + Validation

In the controller I would like to be able to get to the client validation rules of the model. I've attached some attributes using data annotations and would like to be able to pass something back to the client via the ajax call so I can then build the jquery validate options automatically.

Normally this is done for free with the unobtrusive stuff, but I'm trying to leverage knockout binding, while still not having to replicate the validation rules on both the server and client.

Without using reflection on the model server side I'm a little unsure on how to achieve this.


Source: (StackOverflow)

Validate that end date is greater than start date with jQuery

How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?


Source: (StackOverflow)

Error in jquery.validate.js in MVC 4 Project with jQuery 1.9

I created a new ASP.Net MVC 4 project using the template in Visual Studio 2012. After upgrading to jQuery 1.9, the login functionality breaks. Specifically, I get the error

0x800a138f - JavaScript runtime error: Unable to get property 'call' of undefined or null reference

at line 1172, column 5 in jquery.validate.js

How can I fix this issue?


Source: (StackOverflow)

jQuery Validate Plugin - Trigger validation of single field

I've got a form that can optionally be pre-populated via facebook connect. Once a user connects, their name and email are automatically filled in. The problem is that this doesn't trigger the remote validation to check if the email already exists.

Is there a way I could call the validation on that field alone? Something like:

$('#email-field-only').validate()

would be idea. Searched through the docs with no luck.


Source: (StackOverflow)

JQuery Validate multiple fields with one error

How would I use the JQuery Validate plugin to have one error message for say 3 fields. For example 3 dob fields. By default I will get 3 error messages if all 3 fields are left blank. I only want one error linked to 3 fields. If any are blank the error comes up.


Source: (StackOverflow)

jQuery Validation plugin: disable validation for specified submit buttons

I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.

My situation:

It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?

The Buy and Sell a House sample at http://jquery.bassistance.de/validate/demo/multipart/ allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.

The following is a shortened version of the immediately applicable script that I've got right now:

var container = $("#<%= Form.ClientID %> div.validationSuggestion");

$('#<%= Form.ClientID %>').validate({          
    errorContainer: container,
    errorLabelContainer: $("ul",container),
    rules: {
        <%= YesNo.UniqueID %>: { required: true },
        <%= ShortText.UniqueID %>: { required: true } // etc.

    },
    messages: {
        <%= YesNo.UniqueID %>: 'A message.',
        <%= ShortText.UniqueID %>: 'Another message.' // etc.
    },
    highlight: function(element, errorClass) {
        $(element).addClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").removeClass("valid");
    },
    unhighlight: function(element, errorClass) {
        $(element).removeClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").addClass("valid");
    },
    wrapper: 'li'
}); 

Much thanks in advance for helpful pointers.

[UPDATE] Thanks to redsquare I discovered it's as easy as adding class="cancel" to the submit button. So easy and yet I have no idea how I did not come across it in all my searching.

And for those who say my my follow-up answer regarding "but requires a double-click": this was merely due to a leftover experiment line that was unbinding the event - again something I don't know how I overlooked when testing. Thanks!


Source: (StackOverflow)

Bootstrap 3 with jQuery Validation Plugin

I am trying to add validation to my form with jQuery Validation Plugin, but I'm having a problem where the plugin puts the error messages when I'm using input groups.

the problem

$('form').validate({
    rules: {
        firstname: {
            minlength: 3,
            maxlength: 15,
            required: true
        },
        lastname: {
            minlength: 3,
            maxlength: 15,
            required: true
        }
    },
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    }
});

My code: http://jsfiddle.net/hTPY7/4/


Source: (StackOverflow)

How to clear Jquery validation error messages?

I am using jquery validation plugin for client side validation. Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

function clearUser() {
// Need to clear previous errors here
}


function editUser(){    
    var validator = $("#editUserForm").validate({
            rules: {                            
                userName: "required"
        }, 
        errorElement: "span" ,               
        messages: {
          userName: errorMessages.E2
        }
      });

     if(validator.form()){ 
        // form submition code

    }
}

Thanks


Source: (StackOverflow)

jQuery Validate - require at least one field in a group to be filled

I'm using the excellent jQuery Validate Plugin to validate some forms. On one form, I need to ensure that the user fills in at least one of a group of fields. I think I've got a pretty good solution, and wanted to share it. Please suggest any improvements you can think of.

Finding no built-in way to do this, I searched and found Rebecca Murphey's custom validation method, which was very helpful.

I improved this in three ways:

  1. To let you pass in a selector for the group of fields
  2. To let you specify how many of that group must be filled for validation to pass
  3. To show all inputs in the group as passing validation as soon as one of them passes validation. (See shout-out to Nick Craver at end.)

So you can say "at least X inputs that match selector Y must be filled."

The end result, with markup like this:

<input class="productinfo" name="partnumber">
<input class="productinfo" name="description">

...is a group of rules like this:

// Both these inputs input will validate if 
// at least 1 input with class 'productinfo' is filled
partnumber: {
   require_from_group: [1,".productinfo"]
  }
description: {
   require_from_group: [1,".productinfo"]
}

Item #3 assumes that you're adding a class of .checked to your error messages upon successful validation. You can do this as follows, as demonstrated here.

success: function(label) {  
        label.html(" ").addClass("checked"); 
}

As in the demo linked above, I use CSS to give each span.error an X image as its background, unless it has the class .checked, in which case it gets a check mark image.

Here's my code so far:

jQuery.validator.addMethod("require_from_group", function(value, element, options) {
    var numberRequired = options[0];
    var selector = options[1];
    //Look for our selector within the parent form
    var validOrNot = $(selector, element.form).filter(function() {
         // Each field is kept if it has a value
         return $(this).val();
         // Set to true if there are enough, else to false
      }).length >= numberRequired;

    // The elegent part - this element needs to check the others that match the
    // selector, but we don't want to set off a feedback loop where each element
    // has to check each other element. It would be like:
    // Element 1: "I might be valid if you're valid. Are you?"
    // Element 2: "Let's see. I might be valid if YOU'RE valid. Are you?"
    // Element 1: "Let's see. I might be valid if YOU'RE valid. Are you?"
    // ...etc, until we get a "too much recursion" error.
    //
    // So instead we
    //  1) Flag all matching elements as 'currently being validated'
    //  using jQuery's .data()
    //  2) Re-run validation on each of them. Since the others are now
    //     flagged as being in the process, they will skip this section,
    //     and therefore won't turn around and validate everything else
    //  3) Once that's done, we remove the 'currently being validated' flag
    //     from all the elements
    if(!$(element).data('being_validated')) {
    var fields = $(selector, element.form);
    fields.data('being_validated', true);
    // .valid() means "validate using all applicable rules" (which 
    // includes this one)
    fields.valid();
    fields.data('being_validated', false);
    }
    return validOrNot;
    // {0} below is the 0th item in the options field
    }, jQuery.format("Please fill out at least {0} of these fields."));

Hooray!

Shout out

Now for that shout-out - originally, my code just blindly hid the error messages on the other matching fields instead of re-validating them, which meant that if there was another problem (like 'only numbers are allowed and you entered letters'), it got hidden until the user tried to submit. This was because I didn't know how to avoid the feedback loop mentioned in the comments above. I knew there must be a way, so I asked a question, and Nick Craver enlightened me. Thanks, Nick!

Question Solved

This was originally a "let me share this and see if anybody can suggest improvements" kind of question. While I'd still welcome feedback, I think it's pretty complete at this point. (It could be shorter, but I want it to be easy to read and not necessarily concise.) So just enjoy!

Update - now part of jQuery Validation

This was officially added to jQuery Validation on 4/3/2012.


Source: (StackOverflow)

jquery.validate.unobtrusive not working with dynamic injected elements

I am working with ASP.Net MVC3, the easier way to use the client validation would be enabling the jquery.validate.unobtrusive. Everything works fine, for stuff that's right from server.

But when I try to inject some new 'inputs' with javascript, and I knew that I need to call $.validator.unobtrusive.parse() to rebind the validations. But still, all those dynamic injected fields are not functioning.

Even worse, I try to manually bind using jquery.validate and it is not working either. Any thoughts?


Source: (StackOverflow)

jQuery Validate Required Select

I am trying to validate html select element using jQuery Validate plugin. I set "required" rule to true but it always passes validation because zero index is chosed by default. Is there any way to define empty value that is used by required rule?

UPD. Example. Imagine we have the following html control:

<select>
  <option value="default">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

I want Validation plugin to use "default" value as empty.


Source: (StackOverflow)

How can I use jQuery validation with the "chosen" plugin?

I have some <select> inputs using the chosen plugin that I want to validate as "required" on the client side. Since "chosen" hides the actual select element and creates a widget with divs and spans, native HTML5 validation doesn't seem to work properly. The form won't submit (which is good), but the error message is not shown, so the user has no idea what's wrong (which is not good).

I've turned to the jQuery validation plugin (which I planned on using eventually anyways) but haven't had any luck so far. Here's my test case:

<form>
    <label>Name: <input name="test1" required></label>
    <label>Favorite Color:
        <select name="test2" required>
            <option value=""></option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
        </select>
    </label>
    <input type="submit">
</form>
$(document).ready(function(){
    $('select').chosen();
    $('form').validate();
});

This is letting the select through with an empty value, without validating or showing the error message. When I comment out the chosen() line, it works fine.

How can I validate chosen() inputs with the jQuery validation plugin, and show the error message for invalid ones?


Source: (StackOverflow)

jQuery Validation plugin - Validating hidden inputs and not visible? [duplicate]

This question already has an answer here:

How would I validate hidden inputs and not visible text inputs with jQuery Form Validation plugin? The problem is, that I'm using auto-suggest plugin, which generates a hidden input for selected items:

<input id="hiddenInput" type="hidden" name="something" value="1" />

I have 2 inputs like this (both of them only allow 1 item), which I want to validate and display the error in parent <td>. This is what I've gotten so far, but it doesn't display the error or submit a form, if the value is actually a number.

$("#form1").validate({
        rules: {
            something: {
                number:true,
                min:1,
                required:true
            }
        }
        })

Source: (StackOverflow)