admin管理员组文章数量:1314514
I'm using React Hook Form to make an input for height, weight and length. The value cannot be 0 - it has to be at least 1 or more. I tried different ways such as: pattern with regex, validate and more. But I am unable to figure out how to prevent the input field from letting the user type in '0' ( only as the first character ). I also tried type="number" and min="1" however it's not changing anything. Any ideas would be greatly appreciated.
<Input
{...form.register(`pallets.${index}.weight`, {
required: t('errors.emptyInput'),
pattern: {
value: /^[^1-9]/,
message: 'hello',
},
validate: (value) => {
return [/^[^1-9]/].every((pattern) => pattern.test(value))
},
})}
type='number'
/>
It appears to me that pattern
does not change anything. Only type= 'number'
actually affects the way the input field works.
I'm using React Hook Form to make an input for height, weight and length. The value cannot be 0 - it has to be at least 1 or more. I tried different ways such as: pattern with regex, validate and more. But I am unable to figure out how to prevent the input field from letting the user type in '0' ( only as the first character ). I also tried type="number" and min="1" however it's not changing anything. Any ideas would be greatly appreciated.
<Input
{...form.register(`pallets.${index}.weight`, {
required: t('errors.emptyInput'),
pattern: {
value: /^[^1-9]/,
message: 'hello',
},
validate: (value) => {
return [/^[^1-9]/].every((pattern) => pattern.test(value))
},
})}
type='number'
/>
It appears to me that pattern
does not change anything. Only type= 'number'
actually affects the way the input field works.
3 Answers
Reset to default 4<input
type="number"
{...register("test", {
min: 1
})}
/>
You can check the detailed usage from the documentation.
May be try something like this,code might need some syntax fixes
I was struggling with limiting user input to some specific value, { mode: 'onChange' }
worked for me
const { control } = useForm({ mode: 'onChange' });
<Controller
control={control}
name='inputName'
rules={{
min: {
value: 1,
message: 'Value must be between 1 and 100.',
},
max: {
value: 100,
message: 'Value must be between 1 and 100.',
},
}}
render={({ field, fieldState }) => (
<Input
type='number'
controlId='input-id'
value={field.value}
onChange={event => field.onChange(event)}
/>
{fieldState.error && <span>fieldState.error.message</span>}
)}
/>
Input type "number" is now discouraged, so the following rule works for text inputs:
{
value: /^[0-9]*[1-9][0-9]*$/,
message: 'Input must be a number greater than 0.'
}
This also works with leading zeros, which is useful for human input.
本文标签: javascriptReact hook form only allow numbers greater than 0Stack Overflow
版权声明:本文标题:javascript - React hook form only allow numbers greater than 0 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741966356a2407568.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论