React:Form Validation
UseForm permet de valider les inputs avec:
- required
- min et max
- minLength et maxLength
- pattern
- validate
UseForm fournit les fonctions suivantes:
Register:permet d'ajouter un input avec son nom pour le valider<input {...register('nom')} />
<input
{...register("nom", {
required: 'error message'
})}
/>
<input
{...register("test", {
maxLength : {
value: 2,
message: 'error message'
}
})}
/>
<input
{...register("test", {
minLength: {
value: 1,
message: 'error message'
}
})}
/>
<input
type="number"
{...register('test', {
max: {
value: 3,
message: 'error message'
}
})}
/>
<input
type="number"
{...register("test", {
min: {
value: 3,
message: 'error message'
}
})}
/>
<input
{...register("test", {
pattern: {
value: /[A-Za-z]{3}/,
message: 'error message'
}
})}
/>
<input
{...register("test1", {
validate: {
positive: v => parseInt(v) > 0 || 'error message 1',
lessThanTen: v => parseInt(v) < 10 || 'error message 2',
}
})}
/>
register('firstName', {
onChange: (e) => console.log(e)
})
import React,{useState} from "react";
import { useForm } from 'react-hook-form';
/*importer les styles boostrap*/
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
/*Utilisé les données une fois valider */
const onSubmit = (data) => console.log(data);
return (
<div className="card text-center">
<div className="card-header">
Inscription
</div>
<div className="card-body">
<form onSubmit={handleSubmit(onSubmit)}>
Nom: <input {...register('nom')} className="form-control"/>
Prenom: <input {...register('prenom',
{
required: true,
maxLength: 20,
pattern: /^[A-Za-z]+$/i
}
)
} className="form-control" />
{errors.prenom && <p className="alert alert-danger" role="alert">Prenom is required.</p>}
Age: <input {...register('age',
{
pattern: /\d+/ ,
min: 18,
max: 99
})}
className="form-control"/>
{errors.age && <p className="alert alert-danger" role="alert"> Age>0.</p>}
<input type="submit" />
</form>
</div>
</div>
);
}
export default App;