I'm using React Hook Form in order to validate some simple inputs :
import React from "react";
import useForm from "react-hook-form";
import "./App.css";
function App() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit(onSubmit)}>
<input
className="mkn-input"
name="firstName"
placeholder="First name"
ref={register({
required: true,
maxlength: 20,
message: "invalid first name"
})}
/>
<span> {errors.firstName && errors.firstName.message}</span>
<input
placeholder="Last name"
className="mkn-input"
name="lastName"
ref={register({
pattern: /^[A-Za-z]+$/i,
message: "Invalid last name"
})}
/>
{errors.lastName && <span> errors.lastName.message</span>}
<input
name="age"
type="number"
placeholder="Age"
className="mkn-input"
ref={register({ min: 18, max: 99 })}
/>
<input type="submit" className="mkn-btn" />
</form>
</header>
</div>
);
}
export default App;
But I'm facing a weird issue with showing that errors in the DOM, i also to tried to log them in console but without success, what am I missing ?
the full code :
useFormreturns afieldStateobject which in turn holds theerrors. But beware thatfieldStateis some kind of proxy object and will always log as empty{}even when there are errors!