Skip to content

Instantly share code, notes, and snippets.

@ramizpolic
Last active December 22, 2020 15:22
Show Gist options
  • Save ramizpolic/6581dc91f0111e2a382ea833dba12808 to your computer and use it in GitHub Desktop.
Save ramizpolic/6581dc91f0111e2a382ea833dba12808 to your computer and use it in GitHub Desktop.
Reusable React TypeScript equality validator (for Ant)
import { useMemo } from 'react';
import { TFunction } from 'i18next';
import { useTranslation } from 'react-i18next';
import { RuleObject, RuleRender } from 'antd/lib/form';
import { StoreValue } from 'antd/lib/form/interface';
const equalTo = (
t: TFunction,
): ((field: string, translation_key?: string) => RuleRender) => {
/**
* equalTo creates dynamic and reusable form field equality validator.
*
* Used as validator by invoking:
* (field="password", "password.notEqual")
*
* Returns Validator object:
* validator: (rule: RuleObject, value: StoreValue): Promise<any>
*
* @param t {TFunction}
*/
return (field, translation_key) => {
return ({ getFieldValue }): RuleObject => ({
validator(rule: RuleObject, value: StoreValue) {
if (!value || getFieldValue(field) === value) {
return Promise.resolve();
}
return translation_key
? Promise.reject(
t(translation_key, {
defaultValue: 'Values you entered do not match!',
}),
)
: Promise.reject('Values you entered do not match!');
},
});
};
};
const useFormRules = () => {
const { t } = useTranslation();
return useMemo(
() => ({
equalTo: equalTo(t),
}),
[t],
);
};
export default useFormRules;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment