Mau*_*rte 4 javascript validation react-native yup formik
我在 React Native 上使用Yup. 有两个字段(start_time和end_time),我想比较是否start_time在之后end_time并向用户抛出一条消息。
我阅读mixed.when并试图找出解决方案,但我被它阻止了。
const isSameOrAfterTime = (startTime, endTime) =>
moment(startTime, HOUR_MINUTE_SECONDS_MASK).isSameOrAfter(endTime);
// example - data
// start_time: 08:00:25
// end_time: 10:23:42
Run Code Online (Sandbox Code Playgroud)
start_time: Yup.string().when(['start_time', 'end_time'], {
is: (startTime, endTime) => isSameOrAfterTime(startTime, endTime),
then: Yup.string() // ???
otherwise: // ????
}),
Run Code Online (Sandbox Code Playgroud)
当 start_time 在 end_time 之后时,我想抛出一条消息
使用yup.test来代替。
https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema
const SignupSchema = Yup.object().shape({
// (end_time, screma, self)
start_time: Yup.string()
.test(
'not empty',
'Start time cant be empty',
function(value) {
return !!value;
}
)
.test(
"start_time_test",
"Start time must be before end time",
function(value) {
const { end_time } = this.parent;
return isSameOrBefore(value, end_time);
}
),
end_time: Yup.string()
});
Run Code Online (Sandbox Code Playgroud)
const isSameOrBefore = (startTime, endTime) => {
return moment(startTime, 'HH:mm').isSameOrBefore(moment(endTime, 'HH:mm'));
}
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/awesome-johnson-vdueg
| 归档时间: |
|
| 查看次数: |
7009 次 |
| 最近记录: |