zent
Version:
一套前端设计语言和基于React的实现
95 lines (86 loc) • 1.95 kB
Markdown
order: 16
zh-CN:
title: 校验选项
label: 邮箱
message: 请输入邮箱
message2: 请输入正确的邮箱
helpDesc: 这个字段总会在blur事件触发校验
helpDesc2: 这个字段只会在触发onChange之后才在blur事件触发校验
en-US:
title: Validate Option
label: Email
message: Please input email
message2: Please input correct email
helpDesc: This field always validate when blur.
helpDesc2: This field will validate when blur after change event emitted.
```jsx
import {
Form,
FormError,
FormStrategy,
Validators,
ValidateOption,
} from 'zent';
function RequiredEmail({
label,
name,
helpDesc,
validators,
validateOption = ValidateOption.Empty,
defaultValue = '',
props,
}) {
const model = Form.useField(name, defaultValue, [
Validators.required('{i18n.message}'),
Validators.email('{i18n.message2}'),
...(validators || []),
]);
const onChange = useCallback(
e => {
model.isTouched = true;
model.value = e.target.value;
},
[model]
);
const validate = useCallback(() => {
model.validate(validateOption);
}, [model, validateOption]);
return (
<FormControl label={label} required>
<Input
{...props}
value={model.value}
onChange={onChange}
onBlur={validate}
width={240}
/>
{model.error && <FormError>{model.error.message}</FormError>}
<p style={{ color: '#ababab', fontSize: 12 }}>{helpDesc}</p>
</FormControl>
);
}
function App() {
const form = Form.useForm(FormStrategy.View);
return (
<Form form={form} layout="vertical">
<RequiredEmail
name="email"
label="{i18n.label}:"
helpDesc="{i18n.helpDesc}"
validateOption={
ValidateOption.IncludeUntouched | ValidateOption.IncludeAsync
}
/>
<RequiredEmail
name="email"
label="{i18n.label}2:"
helpDesc="{i18n.helpDesc2}"
validateOption={ValidateOption.IncludeAsync}
/>
</Form>
);
}
ReactDOM.render(<App />, mountNode);
```