Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  184] [ 4]  / answers: 1 / hits: 5436  / 3 Years ago, fri, april 9, 2021, 12:00:00

I'm trying to set up a phone number input in react-hook-form library.
I set input type to number, but it still accepts "e" and "-" chars.
I tried to prevent it like this:


<Controller
name="phone"
control={control}
rules={{ required: true }}
render={({ onChange, value, ref }) => (
<Input
ref={ref}
type="number"
label="phone"
onChange={(e) =>
/[^e]/.test(e.target.value) && onChange(e.target.value)
}
val={value}
/>

But it doesn't work properly.
Any recommendations how to solve this problem?


More From » reactjs

 Answers
1

If you want to prevent certain keys from being pressed, you can surpress the keydown event after the check is failed:


<Input
onKeyPress={(e) => {
if (e.key === "e" || e.key === "-") {
e.preventDefault();
}
}}
/>

But if you allow all keys but validate it after being pressed, you can use the pattern option like this:


<Controller
name="phone"
control={control}
rules={{ required: true, pattern: /^d+$/ }}
render={(props) => {
const { onChange, value, ref } = props.field; // v7. use props if you're using v6
const { error } = props.meta;

return (
<Input
ref={ref}
type="number"
label="phone"
onChange={onChange}
val={value}
/>
);
}}
/>

[#1498] Tuesday, April 6, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;