0% ont trouvé ce document utile (0 vote)
118 vues7 pages

Validation de Formulaire en Reactjs

Transféré par

lemmomo29
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
118 vues7 pages

Validation de Formulaire en Reactjs

Transféré par

lemmomo29
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
Vous êtes sur la page 1/ 7

VALIDATION DE FORMULAIRE EN REACTJS

Pour valider vos formulaires en react vous pouvez utiliser du JavaScript uniquement mais cette manière de faire est trop longue (trop de répétition de code et
très susceptible aux erreurs). Ou vous pouvez utiliser des bibliothèques comme « react hook form », « Formik » ou « Yup ».

Dans notre cas, nous allons utiliser la bibliothèque YUP pour valider le schéma de notre formulaire.

Application :
1. Créez un nouveau projet ReactJS
2. Installez tous les modules nécessaires :

npm install @hookform/resolvers yup


npm install bootstrap

3. Modifier le composant « App.js » comme suit :

import React from "react";


import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from "yup";

function App() {

const validationSchema = Yup.object().shape({


name: Yup.string()
.required("ce champ est obligatoire")
.min(5, "trop petit!")
.max(50, "trop long!"),
email: Yup.string()
.email("email invalide")
.required("l'email est obligatoire"),
password: Yup.string()
.required("Mot de passe est obligatoire")
.matches(/([0-9])/, "Au moins un entier")
.min(8, "Mot de passe doit être plus grand que 8 caractères")
.max(50, "Mot de passe doit être plus petit que 50 caractères"),
confirmPassword: Yup.string()
.oneOf(
[Yup.ref("password"), null],
"Le mot de passe de confirmation ne correspond pas"
),
acceptTerms: Yup.bool().oneOf(
[true],
"Accepter les conditions est obligatoire"
),
});

const { register, handleSubmit, formState, reset } = useForm({


mode: "onBlur",
defaultValues: {
name: "",
email: "",
password: "",
confirmPassword: "",
acceptTerms: false
},
resolver: yupResolver(validationSchema),
});

const { errors } = formState;

const onSubmit = data => {


console.log(data);
reset()
}

return (
<div className="container1">
<h1 className="text-center"><u>Inscription</u></h1>
<form onSubmit={handleSubmit(onSubmit)}>
<table className="table_form">
<tr className="line_form">
<td><label htmlFor="email">Name : </label></td>
<td><input type="text" className="form-control" {...register("name")} name="name" id="name" /></td>
<td><small className="text-danger"> {errors.name?.message} </small></td>
</tr>
<tr className="line_form">
<td><label htmlFor="email">Email : </label></td>
<td><input type="email" className="form-control" {...register("email")} /></td>
<td><small className="text-danger"> {errors.email?.message} </small></td>
</tr>
<tr className="line_form">
<td><label htmlFor="password">Password : </label></td>
<td><input type="password" className="form-control" {...register("password")} name="password" id="password" /></td>
<td><small className="text-danger"> {errors.password?.message} </small></td>
</tr>
<tr className="line_form">
<td><label htmlFor="confirmPassword">ConfirmPassword : </label></td>
<td><input type="password" className="form-control" {...register("confirmPassword")} name="confirmPassword" id="confirmPassword" /></td>
<td><small className="text-danger"> { errors.confirmPassword ?.message } </small></td>
</tr>
<tr className="line_form">
<td><label htmlFor="acceptTerms" className="form-check-label"> J'ai lu et j'accepte les conditions </label></td>
<td><input type="checkbox" className="form-check-input" {...register("acceptTerms")} name="acceptTerms" /></td>
<td><small className="text-danger d-block"> {errors.acceptTerms?.message} </small></td>
</tr>
<tr className="line_form">
<td></td>
<td><button type="submit" className="btn btn-primary">S'inscrire</button></td>
<td><button type="button" className="btn btn-danger" onClick={() => reset()}>Annuler</button></td>
</tr>
</table>
</form>
</div>
);
};

export default App;

4. Modifier le fichier « index.css » comme suit :

body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

.App {
text-align: center;
}

@media (prefers-reduced-motion: no-preference) {


.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

.text-center{
text-align: center;
}

.container1{
margin: auto;
width: 60%;
height: 420px;
background-color: rgb(129, 198, 230);
border: 5px solid #4f02b3;
border-radius: 10px;
box-shadow: 10px 10px #f30909;
}

.table_form{
margin: auto;
font-weight: bold;
font-size: 16px;
width: 90%;
}

input{
font-size: 16px;
}

small{
color: #f30909;
}

.line_form{
height: 50px;
}

button{
box-shadow: 0 8px 16px 0 rgba(74, 40, 226, 0.2), 0 6px 20px 0 rgba(214, 40, 147, 0.19);
width: 200px;
height: 50px;
margin: 10px;
border-radius: 5px;
border: 2px solid #f30909;
background-color: hotpink;
font-size: large;
font-weight: bolder;

button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
background: transparent;
color: #f30909;
}

Vous aimerez peut-être aussi