Unexpected Pattern Validation works when using Controller #1811
-
Hi, there. I have a problem. Usually, when you didn't input anything, even if non-required fields have pattern validation, they are valid. But, when you use Controller, it's not. I don't want to pattern-validate when the fields are not required. Because the fields are non-required. Does anyone know how to solve this? Thank you. https://codesandbox.io/s/my-react-hook-form-test-76j28 import React from "react";
import { useForm, Controller, ErrorMessage } from "react-hook-form";
import "./styles.css";
const MyInput = props => (
<div>
<input type="text" {...props} />
</div>
);
export default function App() {
const { handleSubmit, register, control, errors } = useForm({
mode: "onBlur"
});
return (
<form className="App" onSubmit={handleSubmit(data => console.log(data))}>
<p>I don't want to pattern-validate when it's empty.</p>
<Controller
name="firstName"
placeholder="first name"
as={MyInput}
rules={{
pattern: {
value: /^john$/,
message: "firstName is invalid"
}
}}
control={control}
/>
<ErrorMessage
style={{ color: "red" }}
errors={errors}
name="firstName"
as="p"
/>
<p>It works as expected.</p>
<div>
<input
name="lastName"
placeholder="last name"
ref={register({
pattern: {
value: /^smith$/,
message: "lastName is invalid"
}
})}
/>
</div>
<ErrorMessage
style={{ color: "red" }}
errors={errors}
name="lastName"
as="p"
/>
<button type="submit">submit</button>
</form>
);
} |
Beta Was this translation helpful? Give feedback.
Answered by
bluebill1049
Jun 8, 2020
Replies: 1 comment 2 replies
-
you are missing defautltValue at
the behavior is expected and consistent. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you are missing defautltValue at
Controller
the behavior is expected and consistent.