Dynamically change error messages in Kendo UI validator?

8.8k Views Asked by At

think I have a 2 text fields. Can I change there error messages according to text fields.

Here is a example.

1st text box is a email field and it is required field. So I keep it a error messages in a array :

["this field is required", "enter a valid e mail"]

2 text box is required field. Its error message :

["enter a valid value in the field"] 

but in kendo ui validator like this ...

  var validator = $("#formID").kendoValidator( 
       { messages : {
                     required : "this field is required",
                     email : "enter a valid email address"
       }
       }).data("kendoValidator"); 

How I change these values dynamically according to the text fields error messages??

1

There are 1 best solutions below

0
On

you can create function for both required and email to customize error messages according to html input fields.

<form id="myform">
    <input name="username" required /> <br />
    <input type="email" name="userEmail" required data-message="My custom email message" /> <br />
    <button>Validate</button>
</form>

Script section:

<script>
     $("#myform").kendoValidator({
             messages: {
                 // defines a message for the 'custom' validation rule
                 custom: "Please enter valid value for my custom rule",

                 // overrides the built-in message for the required rule
                 required: function(input) {
                     return getRequiredMessage(input);
                 },

                 // overrides the built-in message for the email rule
                 // with a custom function that returns the actual message
                 email: function(input) {
                     return getMessage(input);
                 }
             },
             rules: {
               custom: function(input) {
                 if (input.is("[name=username]")) {
                     return input.val() === "Tom";
                 }
                 return true;
               }
             }
        });

        function getMessage(input) {
          return input.data("message");
        }
        function getRequiredMessage(input) {
           if (input.is("[name=username]")) {
                     return "User name is required";
                 }
            else
                 return input.attr("name") + " Field is Required";
        }
</script>

Jsfiddle

Here in getRequiredMessage function i customized error message based on input name.

I provided "User name is required" for input username. you can provide the error message even from array if you wish.