Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 354
Damon Avatar asked Jun 28 '26 06:06

Damon


1 Answers

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/

like image 163
Sparky Avatar answered Jun 30 '26 01:06

Sparky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!