ChristyPiffat
ChristyPiffat

Reputation: 379

jQuery Validator needs to check for Required onblur

I am using jQuery validator to validate my fields on a form in a Razor view that includes Kendo textboxes. The validations are set up as data annotations on the models. Everything is working perfectly for validations such as max length, email type, etc. However, I cannot get this to run for required fields until the form is submitted. All the information I have read seems to indicate that this is working as designed. Well, I don't want users to have to do a post-back just to find out that they left out one required field. Isn't there any way to include the data-val-required in the jQuery validator when the user tabs off the text box?

I have tried adding the following to my document ready function, but I can't seem to force a validation to occur on the element:

$('#myForm').validate({
  onfocusout: function (element) {
    var required = $(element).attr('data-val-required');
    if (required) {
      $(element).attr('required', 'required');
      //alert('Element ' + $(element).attr('id') + ' ' + $(element).attr('required'));
      $(element).validate();
    }
});

At this point, I'll even accept a full-scale validation on the entire form when the page loads. I'm much more used to Angular and Breeze that include ALL validations in there, so I am hoping that I just missed an obvious fix for this problem.

The previous question that sort of addressed this subject was for re-editing an input. The solution posed there will not work because I want a validation prior to input being entered--just on the onblur event--or a specific call to validation when the user clicks the submit button before the controller method is called. I am beginning to think this is impossible and really wish we were using something other than Razor. Is there something else that can validate forms easily?

Thanks for all your help!

Upvotes: 1

Views: 2912

Answers (2)

ChristyPiffat
ChristyPiffat

Reputation: 379

The above answer worked as far as running the validation, so I am marking it as correct. However, I had another issue that may be due to either Kendo or some other helper that was interfering with the way the HTML was set up for the inputs. For some reason, there was a data-val=true attribute for all attributes where the data annotation in the model was [Required()], but no required attribute. If I added the required attribute (required="required"), then the answer from @Sparky worked perfectly. Otherwise, the validation just assumed that the input was valid when it was empty. So, I did the following to ensure that the required attribute would always be added and the form inputs validated as needed (and also that the form would be validated for the buttons on the form--will remove cancel button from that list eventually):

$(document).ready(function() {
    var formName = 'myForm';
    var form = $('#' + formName);
    if (form) {
        var $inputs = $('#' + formName + ' input[data-val=true]');
        $inputs.each(function () {
            this.required = true;
        });

        var $buttons = $('#' + formName + ' button');
        $buttons.each(function () {
            this.onclick = function () {
                var validator = $(this.form).validate();
                validator.form();
            };
         });

        form.validate({
            onfocusout: function (element) {
                //alert('Leaving ' + element.name + ' with id = ' + element.id + '. Is it valid? ' + element.validity.valid);
                this.element(element);
            }
        });
    }
});

Upvotes: 0

Sparky
Sparky

Reputation: 98738

Well, I don't want users to have to do a post-back just to find out that they left out one required field.

If that were true, there would be no point in having any client-side validation. In other words, this plugin already prevents posting to the server if any required fields are left blank.

Client-side validation only allows posting to the server when all validation rules are satisfied OR if JavaScript is bypassed/disabled.

The previous question that sort of addressed this subject was for re-editing an input. The solution posed there will not work...

No, the previous asker only thought his problem was caused by re-editing an input. However, the OP simply needed to switch from the default "Lazy" over to "Eager" validation within the onkeyup function to get what he needed. To meet your particular request, simply employ the same technique within the onfocusout callback function.

onfocusout: function(element) {
    this.element(element); // validate element immediately
},

DEMO: http://jsfiddle.net/njfyey46/


Your attempt at this was broken because you've called .validate() within .validate(); and .validate() is only used for initializing the plugin. To validate a single element from within a callback function, you would use the validator.element() method. In your case, this represents the validator.

Also, trying to determine if the field contains the required attribute is not necessary. The plugin already automatically determines which rules have been satisfied and fires the appropriate callback functions.

Upvotes: 1

Related Questions