React Validator - CompareRule
A validation rule that requires validated values to match a specified expression.
To specify a comparison expression, define the comparisonTarget function. Validator compares values to this function's return value. To configure which comparison operator Validator compares values to, specify the comparisonType property.
- import React, { useCallback, useMemo, useRef, useState } from 'react';
- import { TextBox, type TextBoxTypes } from 'devextreme-react/text-box';
- import { Validator, CompareRule } from 'devextreme-react/validator';
- const [password, setPassword] = useState('');
- const passwordComparison = useCallback(() => password, [password]);
- const onPasswordChanged = useCallback((e: TextBoxTypes.ValueChangeEvent) => {
- setPassword(e.value);
- }, [setPassword])
- function App() {
- return (
- <React.Fragment>
- <TextBox
- value={password}
- onValueChanged={onPasswordChanged}
- />
- <TextBox>
- <Validator>
- <CompareRule
- message="Passwords do not match."
- comparisonTarget={passwordComparison}
- />
- </Validator>
- </TextBox>
- </React.Fragment>
- );
- }
See Also
comparisonTarget
Specifies the function whose return value is used for comparison with the validated value.
A value to be compared with the validated value.
The rule is valid if the comparison between the validated value and the return value of the comparisonTarget function evaluates to true. The operator specified by the comparisonType property is used to compare values.
comparisonType
Specifies the operator to be used for comparing the validated value with the target.
message
Specifies the message that is shown if the rule is broken.
You can configure an error message in the following ways:
Specify a hard-coded message:
App.tsx- import { TextBox } from 'devextreme-react/text-box';
- import { Validator, CompareRule } from 'devextreme-react/validator';
- function App() {
- return (
- <TextBox>
- <Validator>
- <CompareRule
- message="My custom message"
- />
- </Validator>
- </TextBox>
- );
- }
Hide the message:
App.tsx- import { TextBox } from 'devextreme-react/text-box';
- import { Validator, CompareRule } from 'devextreme-react/validator';
- function App() {
- return (
- <TextBox>
- <Validator>
- <CompareRule
- message=""
- />
- </Validator>
- </TextBox>
- );
- }
Display the editor's name in the default message (for instance, "Passwords do not match"):
App.tsx- import { TextBox } from 'devextreme-react/text-box';
- import { Validator, CompareRule } from 'devextreme-react/validator';
- function App() {
- return (
- <TextBox>
- <Validator name="Passwords">
- <CompareRule />
- </Validator>
- </TextBox>
- );
- }