Angular Common - Data Validation

This guide provides the detailed information on validation capabilities of DevExtreme editors. It describes how to validate a single editor or a group of editors, display the validation summary, perform remote validation, use a custom validation engine, etc.

View Demo

Validate an Editor Value

Associate a DevExtreme editor with the Validator widget and specify validationRules to validate the editor. The full list of predefined validation rules is available in the Validation Rules Reference section.

app.component.html
app.component.ts
app.module.ts
  • <dx-text-box [(value)]="login" placeholder="Login">
  • <dx-validator>
  • <dxi-validation-rule
  • type="required">
  • </dxi-validation-rule>
  • <dxi-validation-rule
  • type="pattern"
  • pattern="^[a-zA-Z]+$"
  • message="Do not use digits.">
  • </dxi-validation-rule>
  • </dx-validator>
  • </dx-text-box>
  • import { Component } from '@angular/core';
  •  
  • @Component({
  • selector: 'app-root',
  • templateUrl: './app.component.html',
  • styleUrls: ['./app.component.css']
  • })
  • export class AppComponent {
  • login: string;
  • }
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import { DxTextBoxModule, DxValidatorModule } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • BrowserModule,
  • DxTextBoxModule,
  • DxValidatorModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Validate Several Editor Values

Group the Editors

Editors belonging to a single Validation Group can be validated together. All editors on a page are automatically collected in a Default Validation Group, which is suitable when you do not need to validate collections of editors separately. In other cases, define Validation Groups as shown in the following code:

app.component.html
app.component.ts
app.module.ts
  • <dx-validation-group name="loginGroup">
  • <dx-text-box [(value)]="login" placeholder="Login">
  • <dx-validator>
  • <!-- Login validation rules are configured here -->
  • </dx-validator>
  • </dx-text-box>
  • <dx-text-box [(value)]="password" placeholder="Password">
  • <dx-validator>
  • <!-- Password validation rules are configured here -->
  • </dx-validator>
  • </dx-text-box>
  • </dx-validation-group>
  • import { Component } from '@angular/core';
  •  
  • @Component({
  • selector: 'app-root',
  • templateUrl: './app.component.html',
  • styleUrls: ['./app.component.css']
  • })
  • export class AppComponent {
  • login: string;
  • password: string;
  • }
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import { DxTextBoxModule, DxValidatorModule, DxValidationGroupModule } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • BrowserModule,
  • DxTextBoxModule,
  • DxValidatorModule,
  • DxValidationGroupModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Validate the Group

You can validate any group by calling its validate() method in a Button's onClick event handler. You can access the Validation Group via the handler's argument. The Button always validates the group to which it belongs. If the membership is not specified, the Button validates the Default Validation Group.

app.component.html
app.component.ts
app.module.ts
  • <!-- <dx-validation-group name="loginGroup"> -->
  • <dx-text-box [(value)]="login">
  • <dx-validator>
  • <!-- Login validation rules are configured here -->
  • </dx-validator>
  • </dx-text-box>
  • <dx-text-box [(value)]="password">
  • <dx-validator>
  • <!-- Password validation rules are configured here -->
  • </dx-validator>
  • </dx-text-box>
  • <dx-button text="Sign in" (onClick)="signIn($event)"></dx-button>
  • <!-- </dx-validation-group> -->
  • import { Component } from '@angular/core';
  •  
  • @Component({
  • selector: 'app-root',
  • templateUrl: './app.component.html',
  • styleUrls: ['./app.component.css']
  • })
  • export class AppComponent {
  • login: string;
  • password: string;
  • signIn(e) {
  • let result = e.validationGroup.validate();
  • if (result.isValid) {
  • // Submit values to the server
  • }
  • }
  • }
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import {
  • DxTextBoxModule,
  • DxValidatorModule,
  • // DxValidationGroupModule,
  • DxButtonModule
  • } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • BrowserModule,
  • DxTextBoxModule,
  • DxValidatorModule,
  • // DxValidationGroupModule,
  • DxButtonModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Alternatively, you can validate a group using the DevExpress.validationEngine.validateGroup method. Call it without arguments to validate the Default Validation Group:

JavaScript
  • DevExpress.validationEngine.validateGroup();

... or pass the group instance to validate a named group:

JavaScript
  • DevExpress.validationEngine.validateGroup($("#loginGroup").dxValidationGroup("instance"));

Pass the group name instead of the instance if you have created widgets using jQuery.

Vue
App.vue
  • <template>
  • <div>
  • <dx-validation-group
  • :ref="groupRefKey">
  • <dx-text-box>
  • <dx-validator>
  • <dx-required-rule />
  • </dx-validator>
  • </dx-text-box>
  •  
  • <dx-text-box>
  • <dx-validator>
  • <dx-required-rule />
  • </dx-validator>
  • </dx-text-box>
  • </dx-validation-group>
  •  
  • <dx-button
  • text="Sign in"
  • @click="validateGroup"
  • />
  • </div>
  • </template>
  •  
  • <script>
  • import 'devextreme/dist/css/dx.common.css';
  • import 'devextreme/dist/css/dx.light.css';
  •  
  • import DxTextBox from 'devextreme-vue/text-box';
  • import DxValidator, { DxRequiredRule } from 'devextreme-vue/validator';
  • import DxValidationGroup from 'devextreme-vue/validation-group';
  • import DxButton from 'devextreme-vue/button';
  •  
  • export default {
  • components: {
  • DxTextBox,
  • DxValidator,
  • DxRequiredRule,
  • DxValidationGroup,
  • DxButton
  • },
  • data() {
  • groupRefKey: 'targetGroup'
  • },
  • methods: {
  • validateGroup() {
  • this.validationGroup.validate();
  • }
  • },
  • computed: {
  • validationGroup: function() {
  • return this.$refs[this.groupRefKey].instance;
  • }
  • }
  • }
  • </script>
React
App.js
  • import React from 'react';
  •  
  • import 'devextreme/dist/css/dx.common.css';
  • import 'devextreme/dist/css/dx.light.css';
  •  
  • import { TextBox } from 'devextreme-react/text-box';
  • import { Button } from 'devextreme-react/button';
  • import { ValidationGroup } from 'devextreme-react/validation-group';
  • import {
  • Validator,
  • RequiredRule
  • } from 'devextreme-react/validator';
  •  
  • class App extends React.Component {
  • constructor(props) {
  • super(props);
  • this.validateGroup = this.validateGroup.bind(this);
  • this.validationGroup = null;
  • };
  •  
  • validateGroup() {
  • this.validationGroup.instance.validate();
  • }
  •  
  • render() {
  • return (
  • <React.Fragment>
  • <ValidationGroup
  • ref={ref => this.validationGroup = ref}>
  • <TextBox>
  • <Validator>
  • <RequiredRule />
  • </Validator>
  • </TextBox>
  •  
  • <TextBox>
  • <Validator>
  • <RequiredRule />
  • </Validator>
  • </TextBox>
  •  
  • <Button
  • text="Sign in"
  • onClick={this.validateGroup}
  • />
  • </ValidationGroup>
  • <React.Fragment>
  • );
  • }
  • }
  • export default App;

Display Validation Errors

All group validation errors can be displayed in the ValidationSummary widget. The following code shows how to add this widget to a page. The commented-out codelines associate the Validation Summary with a named Validation Group.

app.component.html
app.module.ts
  • <!-- <dx-validation-group name="loginGroup"> -->
  • ...
  • <dx-validation-summary></dx-validation-summary>
  • <!-- </dx-validation-group> -->
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import {
  • // ...
  • // DxValidationGroupModule,
  • DxValidationSummaryModule
  • } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • // ...
  • // DxValidationGroupModule,
  • DxValidationSummaryModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Server-Side Validation

Use the "custom" validation rule that allows you to implement a custom validation function for server-side validation. In this function, perform an HTTP request and, when it succeeds, update the validation state and error message.

app.component.ts
app.component.html
app.module.ts
  • import { Component } from '@angular/core';
  • import { HttpClient, HttpHeaders } from '@angular/common/http';
  •  
  • const requestConfig = {
  • headers: new HttpHeaders({
  • 'Content-Type': 'application/json'
  • })
  • }
  •  
  • @Component({
  • selector: 'app-root',
  • templateUrl: './app.component.html',
  • styleUrls: ['./app.component.css']
  • })
  • export class AppComponent {
  • login: string;
  •  
  • constructor(private http:HttpClient) {
  • this.validateLogin = this.validateLogin.bind(this);
  • }
  •  
  • validateLogin(params) {
  • this.http.post(
  • 'https://www.example.com/services/validate-login',
  • JSON.stringify({
  • login: params.value
  • }),
  • requestConfig
  • ).subscribe(response => {
  • params.rule.isValid = response['result'];
  • params.rule.message = response['message'];
  • params.validator.validate();
  • })
  • return false;
  • }
  • }
  • <dx-text-box
  • [(value)]="login"
  • placeholder="Login">
  • <dx-validator>
  • <dxi-validation-rule
  • type="required"
  • message="Login is required">
  • </dxi-validation-rule>
  • <dxi-validation-rule
  • type="custom"
  • [validationCallback]="validateLogin">
  • </dxi-validation-rule>
  • </dx-validator>
  • </dx-text-box>
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import { DxTextBoxModule, DxValidatorModule } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • BrowserModule,
  • DxTextBoxModule,
  • DxValidatorModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Validate a Custom Value

You can use the DevExtreme validation engine to validate a custom value, for example, a non-DevExtreme editor value or a concatenation of several editor values, by configuring the Validator's adapter option. The following example creates two text boxes and a button. A button click checks that at least one of these text boxes is filled. Their values are provided by the getValue function.

app.component.html
app.component.ts
app.module.ts
  • <div id="contacts" [style.border]="borderStyle">
  • <dx-text-box
  • [(value)]="phone"
  • placeholder="Phone"
  • (onValueChanged)="revalidate()">
  • </dx-text-box>
  • <dx-text-box
  • [(value)]="email"
  • type="email"
  • placeholder="Email"
  • (onValueChanged)="revalidate()">
  • </dx-text-box>
  • </div>
  • <dx-validator
  • [adapter]="adapterConfig">
  • <dxi-validation-rule
  • type="required"
  • message="Specify your phone or email.">
  • </dxi-validation-rule>
  • </dx-validator>
  • <dx-validation-summary></dx-validation-summary>
  • <dx-button
  • text="Contact me"
  • (onClick)="submit($event)">
  • </dx-button>
  • import { Component } from '@angular/core';
  •  
  • @Component({
  • selector: 'app-root',
  • templateUrl: './app.component.html',
  • styleUrls: ['./app.component.css']
  • })
  • export class AppComponent {
  • callbacks = [];
  • phone: string;
  • email: string;
  • borderStyle: string = "none";
  • adapterConfig = {
  • getValue: () => {
  • return this.phone || this.email;
  • },
  • applyValidationResults: (e) => {
  • this.borderStyle = e.isValid ? "none" : "1px solid red";
  • },
  • validationRequestsCallbacks: this.callbacks
  • };
  • revalidate() {
  • this.callbacks.forEach(func => {
  • func();
  • });
  • };
  • submit(e) {
  • let result = e.validationGroup.validate();
  • if (result.isValid) {
  • // Submit values to the server
  • }
  • }
  • }
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import {
  • DxTextBoxModule,
  • DxValidatorModule,
  • DxValidationSummaryModule,
  • DxButtonModule
  • } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • BrowserModule,
  • DxTextBoxModule,
  • DxValidatorModule,
  • DxValidationSummaryModule,
  • DxButtonModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Use a Custom Validation Engine

Each DevExtreme editor allows changing its validation state and error message using the isValid and validationError options, which enables you to use any validation engine or custom validation logic. The following example shows a custom function called validateLogin validating a text box value:

app.component.html
app.component.ts
app.module.ts
  • <dx-text-box
  • [(value)]="login"
  • placeholder="Login"
  • [isValid]="isLoginValid"
  • [validationError]="loginValidationError"
  • (onValueChanged)="validateLogin()">
  • </dx-text-box>
  • import { Component } from '@angular/core';
  •  
  • @Component({
  • selector: 'app-root',
  • templateUrl: './app.component.html',
  • styleUrls: ['./app.component.css']
  • })
  • export class AppComponent {
  • login: string;
  • isLoginValid: boolean;
  • loginValidationError: { message?: string };
  •  
  • constructor() {
  • this.isLoginValid = true;
  • this.loginValidationError = {};
  • }
  •  
  • validateLogin() {
  • if (!this.login) {
  • this.loginValidationError = { message: "Login is required" };
  • this.isLoginValid = false;
  • return;
  • }
  • if (!this.login.match(/^[a-zA-Z0-9]+$/)) {
  • this.loginValidationError = { message: "Login can contain only numbers and letters" };
  • this.isLoginValid = false;
  • return;
  • }
  • this.isLoginValid = true;
  • }
  • }
  • import { BrowserModule } from '@angular/platform-browser';
  • import { NgModule } from '@angular/core';
  • import { AppComponent } from './app.component';
  •  
  • import { DxTextBoxModule } from 'devextreme-angular';
  •  
  • @NgModule({
  • declarations: [
  • AppComponent
  • ],
  • imports: [
  • BrowserModule,
  • DxTextBoxModule
  • ],
  • providers: [ ],
  • bootstrap: [AppComponent]
  • })
  • export class AppModule { }

Knockout Only - Validate a View Model

Validating the view model object rather than the editors allows you to separate validation logic from the UI, reuse it between multiple views and unit-test the implementation. To validate a view model's observable, extend it with an object whose dxValidator field contains the validator configuration. After that, associate a target editor with the validator using the isValid and validationError options.

JavaScript
HTML
  • $(function () {
  • var viewModel = {
  • login: ko.observable("").extend({
  • dxValidator: {
  • validationRules: [{ type: 'required', message: 'Login is required' }]
  • }
  • }),
  • password: ko.observable("").extend({
  • dxValidator: {
  • name: "Password",
  • validationRules: [{ type: 'required' }]
  • }
  • })
  • };
  • ko.applyBindings(viewModel);
  • });
  • <div data-bind="dxTextBox: {
  • value: login,
  • placeholder: 'Login',
  • isValid: login.dxValidator.isValid,
  • validationError: login.dxValidator.validationError
  • }"></div>
  • <div data-bind="dxTextBox: {
  • value: password,
  • mode: 'password',
  • placeholder: 'Password',
  • isValid: password.dxValidator.isValid,
  • validationError: password.dxValidator.validationError
  • }"></div>

Finally, pass the to the DevExpress.validationEngine.registerModelForValidation(model) method to register it in the validation engine. The registered view model can be validated at any point in your application by calling the DevExpress.validationEngine.validateModel(model) method.

JavaScript
  • var viewModel = {
  • //...
  • validateAndLogin: function (params) {
  • var result = DevExpress.validationEngine.validateModel(this);
  • if (result.isValid) {
  • // ...
  • }
  • }
  • };
  •  
  • DevExpress.validationEngine.registerModelForValidation(viewModel);
  • ko.applyBindings(viewModel);