Validation

End-user data entry errors are common and it's the developer's responsibility to prevent associated issues. DevExtreme includes a powerful and flexible validation engine and a number of readily usable validation rules. You can choose from standard restrictions (such as "required","stringLength", etc.) or implement your own logic with any level of detail, including remote validation.

Like the rest in DevExtreme, data validation is consistent across all of our shipping themes.

The DevExtreme validation engine comes with a powerful and straightforward API. This enables you to check validation rules at any points. In addition, you are free to use a custom validation engine but indicate an invalid validation result in a UI using the DevExtreme mechanisms. And vise versa, you can use the DevExtreme validation engine, but indicate an invalid validation result in a custom manner.

Read below to learn how to perform the tasks that can be performed using the DevExtreme Validation.

Similar article is available for the MVVM approach.

View Demo

Watch Video

Associate Editor with Validator

To validate an editor value, associate the UI editor with the dxValidator widget. The first approach is universal and will be described in this topic below.

To validate a DevExtreme editor, the latter should be associated with the dxValidator widget.

Editor-Validator Association

The dxValidator widget validates the editor's value against a predefined set of rules. To define the rules to be checked, assign an array of rules to the validator's validationRules configuration option.

JavaScript
dxValidator({
    validationRules: [
        {
            type: 'required',
            message: 'login is required'
        }, {
            type: 'pattern',
            pattern: '^[a-zA-Z]+$',
            message: 'Do not use digits.'
        }
    ]
});

As you can see, validation rules have the type, message and type-specific fields. The type field specifies the rule type, the message field specifies the message to be displayed if a rule is not satisfied. Rule type specific fields are required to specify additional conditions for validation. You can see a full structure of each predefined rule type in the Validation Rules Reference section.

NOTE
The message rule field is not required to be specified. There are default messages for each rule type. Moreover, you can personalize the default messages by setting the name of the validated editor for the validator's name configuration option.

To associate an editor with a validator, extend the editor with the dxValidator widget.

HTML
<div>Login:</div>
<div id="login"></div>
JavaScript
$(function() {
    $("#login").dxTextBox({
        value: null,
        placeholder: 'Login'
    }).dxValidator({
        validationRules: [{
            type: 'required'
        }, {
            type: 'pattern',
            pattern: '^[a-zA-Z]+$',
            message: 'Do not use digits.'
        }]
    });
});

Validate Editor Values

The editors that are associated with the dxValidator widget are automatically validated on the event specified by their valueChangeEvent option. You can also validate several editors at once. For this purpose, there are validation methods that validate a validation group. So, you should associate editors with validation groups.

Validation Group

Define Validation Groups

NOTE
Nested validation groups are not supported.

Specify the validationGroup option of an editor's validator.

HTML
<div>Login:</div>
<div id="login"></div>
<div>Password:</div>
<div id="password"></div>
JavaScript
$(function() {
    var validationGroup = "sampleGroup";
    $("#login").dxTextBox({
        value: null,
        placeholder: 'Login'
    }).dxValidator({
        validationRules: [{
            type: 'required'
        }, {
            type: 'pattern',
            pattern: '^[a-zA-Z]+$',
            message: 'Do not use digits.'
        }],
        validationGroup: validationGroup
    });
    $("#password").dxTextBox({
        mode: 'password'
    }).dxValidator({
        validationRules: [{
            type: 'required',
            message: 'Password is required'
        }],
        validationGroup: validationGroup
    });
});
NOTE
You do not have to combine editors into a single validation group, because the editors that are not associated with a validation group explicitly are combined to a default validation group.

Validate Groups

To validate a group, use one of the following approaches.

  • At a button's click event
    Associate a dxButton widget with the required validation group. In this instance, the associated group will come in the validationGroup field of the parameter passed to a button's click event handler. Call the validate() method of the button's validation group.

    To associate the dxButton widget with a validation group, use the widget's validationGroup configuration option.

    HTML
    <div id="loginButton"></div>
    JavaScript
    var validationGroup = "sampleGroup";
    //...
    $("#loginButton").dxButton({
        text: "Login",
        validationGroup: validationGroup,
        onClick: function(params) {
            var result = params.validationGroup.validate();
            if (result.isValid) {
                DevExpress.ui.notify({
                    message: "You are logged in jQuery as " + $("#login").dxTextBox("instance").option("value"),
                    position: {
                        at: "right top",
                        my: "right top"
                    }
                }, "success", 3000);
            }
        }
    });
    NOTE
    If you are going to use a button to validate the default validation group, do not associate the button with a validation group. The default validation group will come in the parameter object of the click event handler.
  • At any place
    Call the DevExpress.validationEngine.validateGroup(group) method passing the required validation group as a parameter.

    JavaScript
    DevExpress.validationEngine.validateGroup("sampleGroup");
NOTE
To validate the default validation group, call the DevExpress.validationEngine.validateGroup() method without parameters.

Whenever you force validation for a group when an editor value has not changed since the last validation, validation will not be performed repeatedly for this editor. For example, if an editor value has not changed since it was validated on a value change, it will not be validated on a button click when a validation group is validated. However, some rules have the reevaluate option, which allows you to change this behavior and check the required rules no matter the target value changed.

Display Validation Errors

The DevExtreme Validation comes with an integrated UI part. First, each editor is highlighted to indicate that it has an invalid value, when a validation rule is not satisfied during validation.

Validated Editors

Second, a summary on all the validation rules that are not satisfied in a validation group is displayed by the dxValidationSummary widget. This widget has an item collection that is populated each time a validation error occurs in the validation group with which the widget is associated. The summary items are displayed using the default item template that is based on the messages specified for the failed validation rules. You can use a custom item template, as in any collection widget in DevExtreme.

See Also

Validation Summary

To associate the dxValidationSummary widget with a validation group, use the widget's validationGroup configuration option.

HTML
<div>Login:</div>
<div id="login"></div>
<div>Password:</div>
<div id="password"></div>
<div id="summary"></div>
<div id="loginButton"></div>
JavaScript
var validationGroup = "sampleGroup";
//...
$("#summary").dxValidationSummary({
    validationGroup: validationGroup
});
NOTE
You do not have to associate the dxValidationSummary widget with a validation group if you are going to use this widget to display errors occurring in the default validation group.

Remote Scenarios

When validation requires a request to a server, some time may pass until a response from the server comes. Thus, validation should be performed with a delay. Therefore, we recommend that you use the 'custom' rule for such remote scenarios. The 'custom' rule allows you to define a function where you can validate the editor value yourself.

Below, you can see an example where two fields must be validated. One of these fields demands a request to a server. Thus, this field will be validated within the validationCallback function of a 'custom' rule.

To emulate a request to a server, a validation will be performed after the specified timeout. While waiting for the specified timeout, the editor value can be considered either valid or invalid. Choose the scenario that is most appropriate for your application.

HTML
<div id="login"></div>
<img id="image" style="position: absolute; right:10px; top: 9px; visibilty: hidden" src="../Images/preloader.gif" />
<div id="password"></div>
<div id="summary"></div>
<div id="button"></div>
JavaScript
$(function() {
    var checkLoginAvailable;
    var register;
    $("#login").dxTextBox({
        value: null,
        placeholder: 'Login'
    }).dxValidator({
        validationRules: [{
            type: 'required',
            message: 'Login is required'
        }, {
            type: 'custom',
            validationCallback: checkLoginAvailable,
            message: 'This login is not available, please choose another one.'
        }]
    });
    $("#password").dxTextBox({
        value: null,
        mode: 'password',
        placeholder: 'Password'
    }).dxValidator({
        validationRules: [{
            type: 'required',
            message: 'Password can not be empty.'
        }]
    });
    $("#summary").dxValidationSummary({});
    $("#button").dxButton({
        text: 'Register', onClick: register
    });        
});

Positive Scenario

Show Example:
AngularJS
Knockout
jQuery

In this example, the 'Login' editor is considered valid while waiting a response from a server. Enter the 'Alex' login to get a negative response from the server and see how the 'custom' rule is broken.


                                    

                                    

In this example, the 'Login' editor is considered valid while waiting a response from a server. Enter the 'Alex' login to get a negative response from the server and see how the 'custom' rule is broken.


                                    

                                    

In this example, the 'Login' editor is considered valid while waiting a response from a server. Enter the 'Alex' login to get a negative response from the server and see how the 'custom' rule is broken.


                                    

                                    

Negative Scenario

Show Example:
AngularJS
Knockout
jQuery

In this example, the 'Login' editor is considered invalid while waiting a response from a server. Enter the 'Alex' login to get a negative response from the server and see how the 'custom' rule is broken.


                                    

                                    

In this example, the 'Login' editor is considered invalid while waiting a response from a server. Enter the 'Alex' login to get a negative response from the server and see how the 'custom' rule is broken.


                                    

                                    

In this example, the 'Login' editor is considered invalid while waiting a response from a server. Enter the 'Alex' login to get a negative response from the server and see how the 'custom' rule is broken.


                                    

                                    

Validate Custom Editors

There can be scenarios when you cannot associate the dxValidator widget with an editor, because this editor is not a DevExtreme editor or a validated value is a concatenation of several DevExtreme editor values. In this instance, create the dxValidator widget and specify an adapter for it using the adapter configuration option. An adapter is required to "tell" the dxValidator what and when to validate and how to apply the validation result.

The adapter option of the dxValidator widget is an object that exposes the following fields.

  • getValue
    A function that returns the value to be validated.

  • validationRequestsCallbacks
    The jQuery.Callbacks() object that is fired when the specified value should be validated. The dxValidator widget will add a handler to this object, in which it will call its validate function.

  • applyValidationResults
    A function that the dxValidator widget calls after validating the specified value. This function should apply the validation result that the validator passes as a parameter. The validation result is an object. You can see its structure in the description of the dxValidator.validated event argument.

  • reset
    A function that resets the validated values so that end users can then specify other values. This function is called by the reset method of the dxValidator widget.

  • focus
    A function that sets focus to the validated editors when the dxValidationSummary is focused.

  • bypass
    A function that returns a Boolean value specifying whether or not to bypass validation. If the function returns true, validation is bypassed, otherwise validation is performed.

By default, when you do not specify the adapter option, a default adapter is used. The default adapter does the following.

  • Specifies the current value of the associated editor as the getValue function's return value.
  • Fires validationRequestsCallbacks passed to the validator when the event specified by the editor's valueChangeEvent is raised.
  • Sets the editor's isValid and validationError options to the values provided by the validator's validation result.
  • Sets the editor's value to undefined.
  • Focuses the validated editor.
Show Example:
AngularJS
Knockout
jQuery

This example illustrates how to define an adapter for the dxValidator widget, to show a message for an end user when neither an email or phone number is specified.


                                    

                                    

This example illustrates how to define an adapter for the dxValidator widget, to show a message for an end user when neither an email or phone number is specified.


                                    

                                    

This example illustrates how to define an adapter for the dxValidator widget, to show a message for an end user when neither an email or phone number is specified.


                                    

                                    

Use Custom Validation Engine

If you need to use a custom validation engine for DevExtreme editors, but want to display the validation result using the DevExtreme UI implementation, specify the following options for the validated DevExtreme editors.

  • isValid
    Specify whether the current editor value is valid against the validation rules that you checked using your custom validation engine.

  • validationError
    Specify an object that has the message field. This field should be a string that defines the error that occurred during validation.