React:Form Validation

folder Projet: test_react_project
Afin de valider les inputs d'un formulaire ils existent plusieurs méthodes dans ce cours nous allons utilisé le hooks useForm
npm install react-hook-form

UseForm permet de valider les inputs avec:

  1. required
  2. min et max
  3. minLength et maxLength
  4. pattern
  5. validate

UseForm fournit les fonctions suivantes:

Register:permet d'ajouter un input avec son nom pour le valider
<input {...register('nom')} />
-Required
<input
{...register("nom", {
required: 'error message'
})}
/>

-maxLength
<input
{...register("test", {
maxLength : {
value: 2,
message: 'error message'
}
})}
/>

-minLength
<input
{...register("test", {
minLength: {
value: 1,
message: 'error message'
}
})}
/>

-max
<input
type="number"
{...register('test', {
max: {
value: 3,
message: 'error message'
}
})}
/>

-min
<input
type="number"
{...register("test", {
min: {
value: 3,
message: 'error message'
}
})}
/>

-pattern
<input
{...register("test", {
pattern: {
value: /[A-Za-z]{3}/,
message: 'error message'
}
})}
/>

-validate
<input
{...register("test1", {
validate: {
positive: v => parseInt(v) > 0 || 'error message 1',
lessThanTen: v => parseInt(v) < 10 || 'error message 2',
}
})}
/>

-onChange event
register('firstName', {
onChange: (e) => console.log(e)
})


Exemple


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;