Damon
Damon

Reputation: 4484

Set custom validator message using focusout

I would like to show the same message "Please enter your first name." when the user presses submit as well as if/when the foucusout event happens.

Currently, when the user submits, I get the correct message. When I click into the field, and then tab out (focusout) I get "This field is required". I would like to get into the validation method somehow so the messages are consistent.

Here is the markup I am using:

HTML:

<input type="text" id="firstName" name="firstName" />

JavaScript:

var messages = {
    'firstNameRequired': "Please enter your first name."
};


$('input[type="text"]').focusout(function(event) {
    $(this).valid();
});

....

function validateForm() {
    $('#myForm').validate({
        'rules': {
            'firstName': {
                'required': true,
                'minlength': 3
            }
        },
        'messages': {
            'firstName': messages.firstNameRequired
        }
        ...
});

// invalid but this is what I'm trying to accomplish:
 $('input[type="text"]').focusout(function(event) {
    $(this).valid({
        // override the default error message...
        'messages': {
            'firstname': messages.firstNameRequired
         }
    });
});

Thank you for your time!

Upvotes: 3

Views: 15057

Answers (1)

Sparky
Sparky

Reputation: 98728

I've removed the .validate() method from inside your validateForm() function. The problem is caused because you misunderstood the .validate() method. It's not called every time you need validation... it's only called once on page load to initialize the plugin on your form. You're seeing the other messages because the plugin was not initialized properly.

You also don't need the custom external focusout handler. You can use the built-in onfocusout callback like this to achieve the same...

onfocusout: function(element) {
    this.element(element); //< inside 'validate()' method, this is like 'valid()'
},

Do it like this...

$(document).ready(function () {

    var messages = {
        'firstNameRequired': "Please enter your first name."
    };

    $('#myForm').validate({
        rules: {
            firstName: {
                required: true,
                minlength: 3
            }
        },
        messages: {
            firstName: messages.firstNameRequired
        },
        onfocusout: function(element) {
            this.element(element);
        },
        submitHandler: function(form) {
            alert('form is valid');
            return false;
        }
    });

});

DEMO: http://jsfiddle.net/JBL48/

Upvotes: 8

Related Questions