Shivam Pandya
Shivam Pandya

Reputation: 1061

Jquery Validation, Show Custom message with value from id

I Use jquery.validate.js for field validation. Its display error messages as per declare in .js file for appropriate field.

I use this code for custom validation for email field.

 <script type="text/javascript">
    $().ready(function() {
        $("#formcustomplan").validate({
            email: {
                required: true,
                email: true
            },          
            messages: {
                email: "Email is required in valid format"
            }
        });
    });
</script>

Its display message like that "Email is required in valid format" But I want that error message fetch email id and display it in error message. (Ex. if I enter test.com in email box. it should display "test.com is not valid email" in error message)

Here is Fiddle

enter image description here

Upvotes: 2

Views: 3132

Answers (2)

Ryley
Ryley

Reputation: 21226

JQuery Validate actually supports functions as messages directly, so you don't have to do anything super hacky to make this work. It is not well documented but you can do this:

messages: {
    email: {
        email: function (params, element) {
            return '"'+$(element).val()+'" is not a valid value';
        }
    }
}

Quote from the docs:

Each message can be a String or a Callback. The callback is called in the scope of the validator, with the rule’s parameters as the first argument and the element as the second, and must return a String to display as the message.

Working example: http://jsfiddle.net/ryleyb/XUM8k/11/

Upvotes: 1

Felix
Felix

Reputation: 38112

You can reset the default email validation message by using:

$.validator.messages.email = "Your custom message for email field"

In your case, you can prepend the new value from user's input to the custom message. Here is the trick using keyup:

$('.email').keyup(function () {
    $.validator.messages.email = $('.email').val() + ' is not valid email';
});

$("#formcustomplan").validate({
    email: {
        required: true,
        email: true
    }
});

Updated Fiddle

Upvotes: 0

Related Questions