React 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.
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.
- 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 Validator, {
- RequiredRule,
- PatternRule
- } from 'devextreme-react/validator';
- class App extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- login: undefined
- }
- this.setLogin = this.setLogin.bind(this);
- }
- setLogin(e) {
- this.setState({ login: e.value });
- }
- render() {
- return (
- <TextBox
- value={this.state.login}
- placeholder="Login"
- onValueChanged={this.setLogin}>
- <Validator>
- <RequiredRule />
- <PatternRule
- pattern="^[a-zA-Z]+$"
- message="Do not use digits."
- />
- </Validator>
- </TextBox>
- );
- }
- }
- export default App;
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:
- 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 Validator, {
- // Validation rule types are imported here
- } from 'devextreme-react/validator';
- import ValidationGroup from 'devextreme-react/validation-group';
- class App extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- login: undefined,
- password: undefined
- }
- this.setLogin = this.setLogin.bind(this);
- this.setPassword = this.setPassword.bind(this);
- }
- setLogin(e) {
- this.setState({ login: e.value });
- }
- setPassword(e) {
- this.setState({ password: e.value });
- }
- render() {
- return (
- <ValidationGroup name="loginGroup">
- <TextBox
- value={this.state.login}
- placeholder="Login"
- onValueChanged={this.setLogin}>
- <Validator>
- {/* Login validation rules are configured here */}
- </Validator>
- </TextBox>
- <TextBox
- value={this.state.password}
- placeholder="Password"
- onValueChanged={this.setPassword}>
- <Validator>
- {/* Password validation rules are configured here */}
- </Validator>
- </TextBox>
- </ValidationGroup>
- );
- }
- }
- export default App;
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.
- 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 Validator, {
- // Validation rule types are imported here
- } from 'devextreme-react/validator';
- import ValidationGroup from 'devextreme-react/validation-group';
- import Button from 'devextreme-react/button';
- class App extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- login: undefined,
- password: undefined
- }
- this.setLogin = this.setLogin.bind(this);
- this.setPassword = this.setPassword.bind(this);
- this.signIn = this.signIn.bind(this);
- }
- setLogin(e) {
- this.setState({ login: e.value });
- }
- setPassword(e) {
- this.setState({ password: e.value });
- }
- signIn(e) {
- let result = e.validationGroup.validate();
- if (result.isValid) {
- // Submit values to the server
- }
- }
- render() {
- return (
- {/* <ValidationGroup name="loginGroup"> */}
- <TextBox
- value={this.state.login}
- placeholder="Login"
- onValueChanged={this.setLogin}>
- <Validator>
- {/* Login validation rules are configured here */}
- </Validator>
- </TextBox>
- <TextBox
- value={this.state.password}
- placeholder="Password"
- onValueChanged={this.setPassword}>
- <Validator>
- {/* Password validation rules are configured here */}
- </Validator>
- </TextBox>
- <Button
- text="Sign in"
- onClick={this.signIn}
- />
- {/* </ValidationGroup> */}
- );
- }
- }
- export default App;
Alternatively, you can validate a group using the DevExpress.validationEngine.validateGroup method. Call it without arguments to validate the Default Validation Group:
- DevExpress.validationEngine.validateGroup();
... or pass the group instance to validate a named group:
- DevExpress.validationEngine.validateGroup($("#loginGroup").dxValidationGroup("instance"));
Pass the group name instead of the instance if you have created widgets using jQuery.
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
- 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.
- import React from 'react';
- import 'devextreme/dist/css/dx.common.css';
- import 'devextreme/dist/css/dx.light.css';
- // ...
- // import ValidationGroup from 'devextreme-react/validation-group';
- import ValidationSummary from 'devextreme-react/validation-summary';
- class App extends React.Component {
- // ...
- render() {
- return (
- {/* <ValidationGroup name="loginGroup"> */}
- ...
- <ValidationSummary />
- {/* </ValidationGroup> */}
- );
- }
- }
- export default App;
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.
In this example, HTTP requests are performed using the axios library. To replicate the example in your application, install this library:
- npm install axios
- 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 Validator, {
- RequiredRule,
- CustomRule
- } from 'devextreme-react/validator';
- import axios from 'axios';
- const requestConfig = {
- headers: {
- 'Content-Type': 'application/json'
- }
- }
- class App extends React.Component {
- constructor(props) {
- super(props);
- this.login = undefined;
- }
- validateLogin(params) {
- axios.post(
- 'https://www.example.com/services/validate-login',
- JSON.stringify({
- login: params.value
- }),
- requestConfig
- ).then(response => {
- params.rule.isValid = response.data['result'];
- params.rule.message = response.data['message'];
- params.validator.validate();
- })
- return false;
- }
- render() {
- return (
- <TextBox
- value={this.login}
- placeholder="Login">
- <Validator>
- <RequiredRule message="Login is required" />
- <CustomRule validationCallback={this.validateLogin} />
- </Validator>
- </TextBox>
- );
- }
- }
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.
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:
- 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';
- class App extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- login: undefined,
- isLoginValid: true,
- loginValidationError: {}
- }
- this.setLogin = this.setLogin.bind(this);
- }
- setLogin(e) {
- if (!e.value) {
- this.setState({
- login: e.value,
- isLoginValid: false,
- loginValidationError: { message: "Login is required" }
- });
- return;
- }
- if (!e.value.match(/^[a-zA-Z0-9]+$/)) {
- this.setState({
- login: e.value,
- isLoginValid: false,
- loginValidationError: { message: "Login can contain only numbers and letters" }
- });
- return;
- }
- this.setState({
- login: e.value,
- isLoginValid: true,
- loginValidationError: {}
- });
- }
- render() {
- return (
- <TextBox
- value={this.state.login}
- placeholder="Login"
- isValid={this.state.isLoginValid}
- validationError={this.state.loginValidationError}
- onValueChanged={this.setLogin}
- />
- );
- }
- }
- export default App;
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.
- $(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.
- var viewModel = {
- //...
- validateAndLogin: function (params) {
- var result = DevExpress.validationEngine.validateModel(this);
- if (result.isValid) {
- // ...
- }
- }
- };
- DevExpress.validationEngine.registerModelForValidation(viewModel);
- ko.applyBindings(viewModel);
If you have technical questions, please create a support ticket in the DevExpress Support Center.