以 redux 形式验证具有函数作为输入的 prop
Validate prop with function as input in redux form
我对验证道具有疑问。
假设我们(.......)
在组件中我们这样定义:
<Field>
validate = {validate}
</Field>
为什么我们不能写 validate={validate(value)} 或者为什么这样写是不正确的:validate={()=> validate(value)}
谢谢!
Field
上的 validate
属性接受一个函数(或函数数组),该函数应该用于验证传入的字段值。所以你不能写 validate={ someCustomValidator(value) }
除非 someCustomValidator
函数是你定义的函数,而 returns 又是一个函数。
使用 validate={()=> someCustomValidator(value)}
应该有效,但在您的示例的上下文中没有多大意义(value
来自哪里?)。如果您改用 validate={(value)=> someCustomValidator(value)}
,这更有意义,但这是有问题的,因为每次重新呈现带有 Field
的组件时都会创建一个新函数。并根据 documentation:
Note: if the validate prop changes the field will be re-registered.
这可能不是您想发生的事情。
因此,使用
// validation
const someCustomValidator = value => {
// give error roughly half of the time
return Math.random() < 0.5 ?
undefined : // validation is ok
'Validation failed'; // this will be available in meta.error
}
// somewhere else
<Field validate={someCustomValidator} />
才是正确的使用方法。但请注意,Field
内部并不知道如何显示潜在的验证错误。你必须自己解决。有关示例,请参阅 https://redux-form.com/7.0.4/examples/fieldlevelvalidation/。
我对验证道具有疑问。 假设我们(.......) 在组件中我们这样定义:
<Field>
validate = {validate}
</Field>
为什么我们不能写 validate={validate(value)} 或者为什么这样写是不正确的:validate={()=> validate(value)}
谢谢!
Field
上的 validate
属性接受一个函数(或函数数组),该函数应该用于验证传入的字段值。所以你不能写 validate={ someCustomValidator(value) }
除非 someCustomValidator
函数是你定义的函数,而 returns 又是一个函数。
使用 validate={()=> someCustomValidator(value)}
应该有效,但在您的示例的上下文中没有多大意义(value
来自哪里?)。如果您改用 validate={(value)=> someCustomValidator(value)}
,这更有意义,但这是有问题的,因为每次重新呈现带有 Field
的组件时都会创建一个新函数。并根据 documentation:
Note: if the validate prop changes the field will be re-registered.
这可能不是您想发生的事情。
因此,使用
// validation
const someCustomValidator = value => {
// give error roughly half of the time
return Math.random() < 0.5 ?
undefined : // validation is ok
'Validation failed'; // this will be available in meta.error
}
// somewhere else
<Field validate={someCustomValidator} />
才是正确的使用方法。但请注意,Field
内部并不知道如何显示潜在的验证错误。你必须自己解决。有关示例,请参阅 https://redux-form.com/7.0.4/examples/fieldlevelvalidation/。