Pit*_*tty 10 reactjs react-hooks react-hook-form
所以我基本上是新的 with-react-hook-form 我创建了一个带有受控输入的表单,其中第二个输入的条件基于我的第一个输入。我的第一个输入是持续时间,我有两个选项“每月”和“每年”。我的第二个输入是预算,其中每月的最低预算为 200,每年的最低预算为 400。
这是我的代码:
<div style={{ marginTop: theme.spacing(1) }}>
<Controller
as={Select}
row
name="duration"
control={control}
defaultValue="Monthly"
fullWidth
label={<FormattedMessage {...messages.duration} />}
margin="normal"
options={DURATION_OPTIONS}
rules={{
required: 'Required'
}}
/>
</div>
<div>
<Controller
as={NumberField}
row
name="budget"
control={control}
defaultValue="1000"
fullWidth
label={<FormattedMessage {...messages.howMuchBudget} />}
margin="normal"
rules={{
required: true,
min: {
value: 400,
message: 'Min is 400',
}
}}
/>
</div>
Run Code Online (Sandbox Code Playgroud)
现在我想根据我的第一个字段验证动态触发我的第二个字段验证。如果我选择的持续时间为每月,则第二个输入的最小验证应为 200,如果我的持续时间选择为每年,则第二个输入的最小验证应为 400。
任何帮助将不胜感激。
Jay*_*444 10
这是一个基本示例。在这种情况下,姓氏必须比名字短,否则会出现错误。
function App() {
const { register, handleSubmit, errors, getValues } = useForm({mode:'onChange'});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First name</label>
<input name="firstName" defaultValue='Potato' ref={register} />
<label>Last name (must be shorter than first name)</label>
<input name="lastName" ref={register({
validate: {
shorterThanFirstName: value => value.length < getValues().firstName?.length,
}
})} />
{errors.lastName && <p>Last name must be shorter than first name</p>}
<input type="submit" />
</form>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13874 次 |
| 最近记录: |