Validator offers an easy way to do client-side form validation. Built around the HTML5 form validation attributes it supports variety of built-in validation rules, but also provides a convenient way for setting custom rules handling.
<div id="myform">
<input type="text" name="firstName" required />
<input type="text" name="lastName" required />
<button id="save" type="button">Save</button>
</div>
<script>
$(document).ready(function(){
var validatable = $("#myform").kendoValidator().data("kendoValidator");
$("#save").click(function() {
if (validatable.validate()) {
save();
}
});
});
</script>
<input type="text" name="firstName" required />
<input type="text" name="twitter" pattern="https?://(?:www\.)?twitter\.com/.+i" />
<input type="number" name="age" min="1" max="42" />
<input type="number" name="age" min="1" max="100" step="2" />
<input type="url" name="url" />
<input type="email" name="email" />
Beside the built-in validation rules, KendoUI Validator also provides a convenient way for setting custom rules through its rules configuration option.
$("#myform").kendoValidator({
rules: {
custom: function(input) {
// Only Tom will be a valid value for FirstName input
return input.is("[name=firstname]") && input.val() === "Tom";
}
}
});
There are several ways to control the messages which appears if validation fails:
$("#myform").kendoValidator({
rules: {
custom: function(input) {
//...
}
},
messages: {
// defines message for the 'custom' validation rule
custom: "Please enter valid value for my custom rule",
// overrides the built-in message for required rule
required: "My custom required message",
// overrides the built-in email rule message with a custom function which return the actual message
email: function(input) {
return getMessage(input);
}
}
});
<input type="tel" pattern="\d{10}" validationMessage="Plase enter a ten digit phone number" />
In order to trigger the element(s) validation, validate method should be used. It will return either true if validation succeeded or false in case of a failure.
Note that if a HTML form element is set as validation container, the form submits will be automatically prevented if validation fails.
Ideally Kendo Validator places its tooltips besides the validated input. However, if the input is later enhanced to a ComboBox, AutoComplete or other Kendo Widget, placing the tooltip beside the input may cover important information or break the widget rendering. In this case, you can specify where exactly do you want the tooltip to be placed by adding a span with data-for attribute set to the validated input name and a class .k-invalid-msg. Check the example below:
<div id="myform">
<input type="text" id="name" name="name" required />
<span class="k-invalid-msg" data-for="name"></span>
</div>
<script>
$("#name").kendoAutoComplete({
dataSource: data,
separator: ", "
});
$("#myform").kendoValidator();
</script>