Introduction
Rien de plus ennuyeux que de créer des formulaires en HTML et de vérifier champs par champs si l‘utilisateur a correctement rempli les contraintes.
On crée en général un formulaire en HTML5 avec les attributs (voire même couplé au Javascript) comme ceci:
<form method="post" action="/login"> <h1>Mon compte</h1> <input type="email" name="email" placeholder="E-mail" maxlength="100" required/> <input type="password" name="motdepasse" placeholder="Mot de passe" maxlength="30" required/> <input type="submit" name="submit" value="Connexion" /> <form>
Puis on vérifie à nouveau que tous les champs sont fournis et correctement remplis en retapant le nom de chaque élément comme ceci:
if(isset($_POST["email"]) && isset($_POST["password"])){ $email = trim(htmlentities($_POST["email"], ENT_QUOTES, "UTF-8")); $password = trim(htmlentities($_POST["password"], ENT_QUOTES, "UTF-8")); if(!empty($email) && !empty($password)){ if(strlen($_POST["email"]) <= 100 && strlen($_POST["password"])<30){ if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) { // suite des instructions d'authentification }else{ // traitement de l'erreur } }else{ // traitement de l'erreur } }else{ // traitement de l'erreur } }
L’exemple ici est plutôt léger, avouons-le !
Mais le côté ennuyeux s’accentue quand le formulaire s’allonge ou quand on doit créer une tonne de formulaires.
C’est pour cette raison que j’ai créé une classe en PHP qui permet de simplifier la vie.
En effet, il suffit juste de créer une seule fois le formulaire et d’appeler la méthode « check » pour vérifier si le formulaire est bien rempli.
La classe en PHP 8.1:
<?php /* ______ ____ _____ __ __ _____ | ____/ __ \| __ \| \/ |/ ____| | |__ | | | | |__) | \ / | (___ | __|| | | | _ /| |\/| |\___ \ | | | |__| | | \ \| | | |____) | |_| \____/|_| \_\_| |_|_____/ */ namespace class; class form{ public $attr; public $element; /** * Constructor * object = <form ...>...</form> * * @param array $attr MUST contain the attr "method" and "action". Can contain the attribute class. * @param array $element Elements of the form (input, texarea, ...). * @param boolean $token CRSF token */ public function __construct(array $attr, array $element = array(), bool $token = true){ $this->method = (array_key_exists('method', $attr)) ? $attr["method"] : ""; $this->action = (array_key_exists('action', $attr)) ? $attr["action"] : ""; $this->class = (array_key_exists('class', $attr)) ? $attr["class"] : ""; $this->enctype = (array_key_exists('enctype', $attr)) ? $attr["enctype"] : ""; $this->element = $element; $this->token = $token; // i add a hidden input in the form with the token if enabled if($token){ $this->setElement("input", array( "type" => "hidden", "name" => "token", "value" => \class\token::gen(), "class" => "form-control" )); } } /** * Add element into a form * * @param string $tag * @param array $attribut * @param array $html (can contain the key "before" and "after" for add HTML or text before or after the element) * @return void */ public function setElement(string $tag, array $attribut, array $html=array()):void{ $element = array(); // input, button $tag = trim(strtolower($tag)); if($tag=="input" || $tag=="button" || $tag=="textarea" || "select"){ $element["tag"] = $tag; $element["attributList"] = $attribut; $element["html"] = $html; $this->element[] = $element; }else{ if(PROD==false){ trigger_error("<p class='dev_critical'>Error « $tag » : is not yet compatible...</p>", E_USER_ERROR); } } } /** * Display form as HTML format * * @return string */ public function display():string{ $return = "<form action='{$this->action}' method='{$this->method}' class='{$this->class}' enctype='{$this->enctype}'>"; // start of the string foreach($this->element as $k => $arrayElement){ if(array_key_exists('tag', $arrayElement)){ if(array_key_exists('attributList', $arrayElement)){ if(array_key_exists('name', $arrayElement["attributList"])){ // add HTML after or before an element if(gettype($arrayElement["html"])=="array"){ $htmlBefore = (array_key_exists('before', $arrayElement["html"])) ? $arrayElement["html"]["before"] : ""; $htmlAfter = (array_key_exists('after', $arrayElement["html"])) ? $arrayElement["html"]["after"] : ""; }else{ if(PROD==true){ trigger_error("<p class='dev_critical txt-center'>The third element in the method setElement must be an array. This array can contain the keys 'before' and 'after'.</p>", E_USER_ERROR); } } $tag = format::normalize($arrayElement["tag"]); $attr = ""; if($tag=="input"){ foreach($arrayElement["attributList"] as $attribute => $attrValue){ if($attribute!="html"){ $attr .= " {$attribute}='{$attrValue}'"; } } $return .= "$htmlBefore<$tag $attr />$htmlAfter"; }elseif($tag=="textarea" || $tag=="button"){ foreach($arrayElement["attributList"] as $attribute => $attrValue){ if(trim(strtolower($attribute))!="value"){ if($attribute!="html"){ $attr .= " {$attribute}='{$attrValue}'"; } } } $value = array_key_exists('value', $arrayElement) ? $arrayElement["value"]: ""; $return .= "$htmlBefore<$tag $attr >$value</textarea>$htmlAfter"; }elseif($tag=="select"){ // multiple select debug (1/2) if(in_array(format::normalize("multiple"), $arrayElement["attributList"])){ if(!in_array(format::normalize("required"), $arrayElement["attributList"])){ $arrayElement["attributList"]["required"] = NULL; } } // i continue (multiple or single) foreach($arrayElement["attributList"] as $attribute => $attrValue){ if(trim(strtolower($attribute))!="option"){ if($attribute!="html"){ $attr .= " {$attribute}='{$attrValue}'"; } } } $optionList = ""; if(array_key_exists('option', $arrayElement["attributList"])){ if(gettype($arrayElement["attributList"]["option"])=="array"){ // multiple select debug (1/2) if(in_array(format::normalize("multiple"), $arrayElement["attributList"])){ $arrayElement["attributList"]["option"][NULL]=""; } foreach($arrayElement["attributList"]["option"] as $kOption => $vOption){ $optionList .= "<option value='$kOption'>$vOption</option>"; } }else{ http_response_code(500); if(PROD==false){ trigger_error("<p class='dev_critical txt-center'>Internal error: the key " option " for the " select " must be an array.</p>", E_USER_ERROR); }else{ die("<p class='dev_critical txt-center'>Erreur 500: activez le mode « dev » si vous êtes l'administrateur du site pour plus d'informations.</p>"); } } }else{ if(PROD==false){ trigger_error("<p class='dev_critical txt-center'>Internal error: the key " option " for the " select " is missing.</p>", E_USER_ERROR); } } $return .= "$htmlBefore<$tag $attr>$optionList</$tag>$htmlAfter"; }else{ http_response_code(500); if(PROD==false){ trigger_error("<p class='dev_critical txt-center'>Internal error: type of element unknown</p>", E_USER_ERROR); }else{ die("<p class='dev_critical txt-center'>Erreur 500: activez le mode « dev » si vous êtes l'administrateur du site pour plus d'informations.</p>"); } } }else{ http_response_code(500); if(PROD==false){ trigger_error("<p class='dev_critical txt-center'>Internal error: one or severals element(s) of the form has not name.</p>", E_USER_ERROR); }else{ die("<p class='dev_critical txt-center'>Erreur 500: activez le mode « dev » si vous êtes l'administrateur du site pour plus d'informations.</p>"); } } }else{ http_response_code(500); if(PROD==false){ trigger_error("<p class='dev_critical txt-center'>Internal error: any HTML attribute found for on more more elements</p>", E_USER_ERROR); }else{ die("<p class='dev_critical txt-center'>Erreur 500: activez le mode « dev » si vous êtes l'administrateur du site pour plus d'informations.</p>"); } } }else{ http_response_code(500); if(PROD==false){ trigger_error("<p class='dev_critical txt-center'>Internal error: tag unknown</p>", E_USER_ERROR); }else{ die("<p class='dev_critical txt-center'>Erreur 500: activez le mode « dev » si vous êtes l'administrateur du site pour plus d'informations.</p>"); } } } return $return."</form>"; // end of the string } /** * Return the number of elements expected in the form (all except with the HTML attribute "disabled") * @param array $array * @return string */ private function trueCount(array $elementList):int{ $count = count($elementList); foreach($elementList as $element){ if(array_key_exists("attributList", $element)){ if(array_key_exists("disabled", $element["attributList"])){ if($element["attributList"]["disabled"]=="disabled" || $element["attributList"]["disabled"]=="true"){ $count--; } } } } return $count; } /** * Check if all fields of the form are corrects * * @return array * @return $returnBool If the option is on "true": Return if the form is correct or not (return true if the form is correct else false). If the option is off "false": Return an array of the errors. * */ public function check(bool $returnBool = true):string|bool{ $err = array( "date" => "Format de la date incorrect", "ie" => "Internal error.", "require" => "Tous les champs sont requis ne sont pas complétés.", "nodata" => "Pas de données envoyées.", "minlength" => "Un ou des champs ne respecte pas la longueur minimum requise.", "maxlength" => "Un ou des champs dépasse la longueur maximum.", "email" => "Un ou des champs e-mail invalide(s): vérifiez le format.", "number" => "Un ou des champs incorrect(s): une valeur numérique est attendue.", "min" => "Un ou des champs incorrect(s): une valeur numérique est inférieur à celle attendue.", "max" => "Un ou des champs incorrect(s): une valeur numérique est supérieure à celle attendue.", "hex" => "Un ou plusieur(s) champ(s) couleur HEX invalides.", "unexpectedVal" => "Erreur: valeur(s) non-attendu(s) d'un ou plusieurs menu déroulants.", "unexpectedVal2" => "Erreur: une seule valeur attendue pour un ou plusieurs menu déroulant.", "misElmt" => "Element(s) de formulaire en trop ou manquant.", "token" => "Token invalide ou expiré.", "url" => "Format d'URL invalide." ); $errorList = array(); $methodUsed = (format::normalize($this->method)=="post") ? "POST" : "GET"; $dataSubmit = (format::normalize($this->method)=="post") ? array_merge($_POST, $_FILES) : array_merge($_GET, $_FILES); //var_dump($this->element); if(count($dataSubmit)>0){ // i check if i have data (if the form is submit) if(count($dataSubmit)==form::trueCount($this->element)){ // check if number of parameters get/post // TOKEN CHECK if($this->token){ if(isset($dataSubmit["token"])){ if(token::check($dataSubmit["token"])){ $tokenIsValid = true; }else{ $tokenIsValid = false; $errorList[] = $err["token"]; } }else{ $tokenIsValid = false; $errorList[] = $err["misElmt"]; } }else{ $tokenIsValid = true; // if token is disabled for the form } if($tokenIsValid){ // FIRST ARRAY $elementListNameFromObj = array(); // i create a new array for add the name of all elements form object foreach($this->element as $k => $arrayElement){ // for each element $elementListNameFromObj[] = $arrayElement["attributList"]["name"]; // i add in array the name of all elements from object } // SECOND ARRAY $elementListNameFromSubmit = array(); // array for retrieve all names for elements from submit (i don't will use array_reverse for security reasons and possible conflicts) foreach($dataSubmit as $kDataSubmit => $vDataSubmit){ $elementListNameFromSubmit[] = security::cleanStr($kDataSubmit); } // COMPARE ARRAYS if(sort($elementListNameFromObj) == sort($elementListNameFromSubmit)){ // all names of the form aren't wrong (all input field names from form are expected) foreach($this->element as $k => $arrayElement){ $tag = format::normalize($arrayElement["tag"]); if($tag == "textarea" || $tag == "input" || $tag == "select"){ // CHECK IF FIELD IS REQUIRED $bypassCheckLength = false; if(array_key_exists('required', $arrayElement["attributList"])){ // i check if there the attr required in object // IN THIS FOLLOWING CONDITION WILL CHECK IF I'VE A VALUE IN THE FIELD OR NOT (of my required field) if(gettype($dataSubmit[$arrayElement["attributList"]["name"]]) == "array"){ // for file input $valueField = security::cleanStr($dataSubmit[$arrayElement["attributList"]["name"]]["name"]); }else{ // for all fields except file input $valueField = security::cleanStr($dataSubmit[$arrayElement["attributList"]["name"]]); } if($valueField==""){ $errorList[] = $err["require"]; $bypassCheckLength = true; if(PROD==false){ trigger_error("<p class='dev_critical'>One or more element required bypassed.</p>", E_USER_ERROR); } } } // IT'S NOT NECESSARY TO CHECK MAX/MINLENGTH IF THE REQUIRED FIELD IS EMPTY if($bypassCheckLength == false){ // CHECK IF MAXLENGTH/MINLENGTH $minORmaxLength = array("minlength", "maxlength"); foreach($minORmaxLength as $vMinMax){ if(array_key_exists($vMinMax, $arrayElement["attributList"])){ if(is_numeric(format::normalize($arrayElement["attributList"][$vMinMax]))){ // check if it's an integer if($vMinMax=="minlength"){ if(strlen(format::normalize($dataSubmit[$arrayElement["attributList"]["name"]])) < $arrayElement["attributList"][$vMinMax]){ // if data form form > maxlength $errorList[] = $err["minlength"]; } }else{ if(strlen(format::normalize($dataSubmit[$arrayElement["attributList"]["name"]])) > $arrayElement["attributList"][$vMinMax]){ // if data form form > maxlength $errorList[] = $err["maxlength"]; } } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>$vMinMax MUST BE an integer.</p>", E_USER_ERROR); } } } } } // CHECK OUT IF INPUT TYPE IS NOT WRONG if($tag == "input"){ if(array_key_exists('type', $arrayElement["attributList"])){ if(format::normalize($arrayElement["attributList"]["type"])=="email"){ if (!filter_var($dataSubmit[$arrayElement["attributList"]["name"]], FILTER_VALIDATE_EMAIL)) { $errorList[] = $err["email"]; } }else if(format::normalize($arrayElement["attributList"]["type"])=="url"){ if(array_key_exists("required", $arrayElement["attributList"])){ // IF URL IS REQUIRED if (!filter_var($dataSubmit[$arrayElement["attributList"]["name"]], FILTER_VALIDATE_URL)) { $errorList[] = $err["url"]; } }else{ if(strlen(format::normalize($dataSubmit[$arrayElement["attributList"]["name"]]))>0){ if (!filter_var($dataSubmit[$arrayElement["attributList"]["name"]], FILTER_VALIDATE_URL)) { // if url is not required BUT provided by user $errorList[] = $err["url"]; } } } }else if(format::normalize($arrayElement["attributList"]["type"])=="date"){ if(array_key_exists("required", $arrayElement["attributList"])){ // IF DATE IS REQUIRED if (!validator::dateTime($dataSubmit[$arrayElement["attributList"]["name"]], "Y-m-d")) { $errorList[] = $err["date"]; } }else{ if(strlen(format::normalize($dataSubmit[$arrayElement["attributList"]["name"]]))>0){ // if not required BUT provided by user if (!validator::dateTime($dataSubmit[$arrayElement["attributList"]["name"]], "Y-m-d")) { // check format date $errorList[] = $err["date"]; }else{ if(!validator::dateExist($dataSubmit[$arrayElement["attributList"]["name"]])){ // check if date exist $errorList[] = $err["date"]; } } } } }elseif(format::normalize($arrayElement["attributList"]["type"])=="number" || format::normalize($arrayElement["attributList"]["type"])=="range"){ if(!is_numeric($dataSubmit[$arrayElement["attributList"]["name"]])){ $errorList[] = $err["number"]; }else{ // IF IS THE VALUE IS NUMERIC // attr: min if(array_key_exists("min", $arrayElement["attributList"])){ // if the attribute "min" is init in object if(is_numeric($arrayElement["attributList"]["min"])){ if(intval($dataSubmit[$arrayElement["attributList"]["name"]]) < intval($arrayElement["attributList"]["min"])){ $errorList[] = $err["min"]; } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Check out if the attribute ", min " is a numeric value.</p>", E_USER_ERROR); } } } // attr: max if(array_key_exists("max", $arrayElement["attributList"])){ // if the attribute "min" is init in object if(is_numeric($arrayElement["attributList"]["max"])){ if(intval($dataSubmit[$arrayElement["attributList"]["name"]]) > intval($arrayElement["attributList"]["max"])){ $errorList[] = $err["max"]; } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Check out if the attribute ", min " is a numeric value.</p>", E_USER_ERROR); } } } } }elseif($arrayElement["attributList"]["type"]=="color"){ if(!preg_match('/^#[a-f0-9]{6}$/i', $dataSubmit[$arrayElement["attributList"]["name"]])){ $errorList[] = $err["hex"]; if(PROD==false){ trigger_error("<p class='dev_critical'>One ore more attribute(s) " type " missing in the tag " input ".</p>", E_USER_ERROR); } } } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>One ore more attribute(s) " type " missing in the tag " input ".</p>", E_USER_ERROR); } } } // IF SELECT if($tag=="select"){ if(array_key_exists('option', $arrayElement["attributList"])){ if(gettype($arrayElement["attributList"]["option"])=="array"){ // i check if the option value provided is of type "array" if(array_key_exists("multiple", $arrayElement["attributList"])){ // IF SELECT MULTIPLE EXPECTED // MULTIPLE VALUES RETURNED if(gettype($dataSubmit[$arrayElement["attributList"]["name"]])=="array"){ $cleanArr = format::cleanArr($dataSubmit[$arrayElement["attributList"]["name"]]); if(count($cleanArr)>0){ foreach($cleanArr as $value){ if(!array_key_exists($value, $arrayElement["attributList"]["option"])){ $errorList[] = $err["unexpectedVal"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Security: the value sended form " select " dont't feel be in the object.</p>", E_USER_ERROR); } } } }else{ $errorList[] = $err["unexpectedVal"]; } }else{ // IF ALONE VALUE RETURNED if(!array_key_exists($dataSubmit[$arrayElement["attributList"]["name"]], $arrayElement["attributList"]["option"])){ // i check if the value sended is in array (object) if(array_key_exists("required", $arrayElement["attributList"])){ $errorList[] = $err["unexpectedVal"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Security: the value sended form " select " dont't feel be in the object.</p>", E_USER_ERROR); } } } } }else{ // IF ALONE VALUE EXPECTED if(gettype($dataSubmit[$arrayElement["attributList"]["name"]])=="string"){ if(!array_key_exists($dataSubmit[$arrayElement["attributList"]["name"]], $arrayElement["attributList"]["option"])){ // i check if the value sended is in array (object) $errorList[] = $err["unexpectedVal"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Security: the value sended form " select " dont't feel be in the object.</p>", E_USER_ERROR); } } }else{ $errorList[] = $err["unexpectedVal2"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Security: string expected for " select " field.</p>", E_USER_ERROR); } } } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Check out the element(s) " select ": value of type array expected.</p>", E_USER_ERROR); } } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Check out the element(s) " select ": a dropdown must contain an array with value(s).</p>", E_USER_ERROR); } } } }else{ $errorList[] = $err["ie"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Unrecognized form element (tag).</p>", E_USER_ERROR); } } } }else{ $errorList[] = $err["misElmt"]; if(PROD==false){ trigger_error("<p class='dev_critical'>Check if all submitted data $methodUsed is expected (that there is no more data sent).</p>", E_USER_ERROR); } } } }else{ $errorList[] = $err["misElmt"]; if(PROD==false){ echo "<p>Send:".count($dataSubmit)." elements. Expected: ".form::trueCount($this->element)." elements</p>"; trigger_error("<p class='dev_critical'>Check if each all elements of the form have an attribute « name »</p>", E_USER_ERROR); } } }else{ $errorList[] = $err["nodata"]; } // return data if($returnBool == true){ if(count($errorList) == 0){ return true; }else{ return false; } }else{ return implode("<br>",$errorList); } } } ?>
L’instanciation de l’objet:
Pour créer l’objet, il suffit d’instancier l’objet.
Dans l’instanciation il faut indiquer la méthode (« get » ou « post » et l’action du formulaire (« cible »).
Ajouter des éléments
Généralités
Pour créer un élément de formulaire: il suffit de spécifier le tag (input, button, textarea, …) et ses attributs HTML5 dans la méthode « setElement ».
Ses attributs peuvent-être les suivants (liste non-exhaustive):
- type
- value
- placeholder
- name
- classe
- required
- minlength
- maxlength
- multiple
- selected
- disabled
$formLogin = new form(array( // i declare my new object "method" => "post", // i give the method attr "action" => "", // i give action attr "class"=>"login", // i give className ou className list (not required) )); $formLogin->setElement("input", array( // here i give the type of tag "type" => "text", // i give the type of input "placeholder" => "Username", // i set a placeholder "name" => "username", // i give a className "required" => "required", // i add the attr required "minlength" => 4, "maxlength" => 25 )); $formLogin->setElement("input", array( "type" => "password", "placeholder" => "Enter your password", "name" => "password", "minlength" => 3, "maxlength" => 25 )); $formLogin->setElement("input", array( "type" => "color", "placeholder" => "#fffff", "name" => "color", )); $formLogin->setElement("input", array( "type" => "submit", "value" => "Log in", "name" => "submit", "class" => "btn btn-primary" // i add a class to the element ));
⚠️ Il est recommandé d’utiliser les entités HTML pour les guillemets si vous souhaitez les utiliser en tant que texte.
Exemple:
$formLogin->setElement("input", array( "class"=>"myClass", "type" => "email" "value" => "Entrez une "vraie" adresse" ));
ℹ️ La majorité des attributs et types sont supportés par la classe PHP.
ℹ️ La classe vérifie:
- si le type format est valide pour les champs e-mail et nombre
- si le nombre spécifié dans champs de type nombre ou intervalle est dans l’intervalle s’il est défini
- les attributs maxlength et minlength
- si le champs requis n’est pas vide
- si la valeur d’un champ de couleur est valide
- si le ou les valeurs sont dans le menu « select » lors de la vérification
⚠️ L’attribut « pattern » n’est pas encore supporté
⚠️ La classe ne supporte pas encore la vérification des valeurs des champs de type « radio » ou « checkbox »
Menu déroulant (« select »)
Pour le menu déroulant (« select ») vous devez créer un tableau associatif pour la clé « option ».
Le menu déroulant multiple est supporté par la classe.
Exemple d’un élément « select »:
$formLogin->setElement("select", array( "class"=>"myClass", "option" => array( "1" => "Accueil", "2" => "Ma page perso" ) ));
Ajouter du contenu avant ou après l’élément
L’utilisation de la clé « data-gngLabel » est désormais deprecié.
Il faut désormais utiliser une clé « html » de type array. Cette dernière doit contenir la clé « before » pour ajouter du contenu avant l’élément. Et/ou « after » pour ajouter du contenu après.
Exemple:
$formLogin->setElement("input", array( // here i give the type of tag "type" => "text", // i give the type of input "placeholder" => "Nom d'utilisateur", // i set a placeholder "name" => "username", // i give a className "required" => "required", // i add the attr required "minlength" => $gng_paramList->get("usernameMinLength"), // i add the attr minlength "maxlength" => $gng_paramList->get("usernameMaxLength"), // i add the attr maxlength "class" => "form-control" ), // add content after or before the element array( "before" => "<b>text before</b>", "after" => "</i>text after</i>" ) );
Vérification de la saisie
La méthode « check » de classe retourne le tableau (« array ») des erreurs si le paramètre est sur « false ».
Sinon (si le paramètre est sur « true » ou la valeur par défaut) une valeur boolean est retournée (true = formulaire correctement rempli, false = formulaire falsifié ou mal rempli).
⚠️ Tous les éléments doivent contenir un attribut « name » pour employer cette méthode !
if($formLogin->check()){ // continue.. }
L’affichage du formulaire:
Pour afficher le formulaire, rien de plus simple:
$formLogin->display();
Remarques
→ L’utilisateur sera retoqué même s’il bidouille le formulaire.
→ Le classe peut-être utilisé pour un projet écrit en spaghettis ou en MVC.
L’autre avantage c’est qu’il n’y a pas de risques de divergence entre les exigences (longueur max/min, type, …) dans la partie front et la partie back.
⚠️ Les autres classes nécessaires au bon fonctionnement de cette classes sont disponibles sur le dépôt github suivant: https://github.com/cyrilovh/geneager/tree/dev/src/class
Mises à jour:
29/07/2022:
- débogage: variable $tokenIsValid introuvable quand le système anti-CRSF est désactivé
- Attribut HTML « disabled » pris en charge (plus de divergence à la vérification de l’intégrité du formulaire):
- méthode trueCount implementée
- Nouvelles fonctionnalités:
- vérifie si la date existe et valide
- verifie si l’URL est valide
13/07/2022: Débogage champs « file » requis (ligne 258)
07/07/2022: Débogage d’un formulaire contenant un fichier (enctype)
28/06/2022:
– Debogages pour le textarea
– Ajout d’un paramètre à la méthode « check »
-> Cette version sera la dernière sur le blog. Mais si vous le souhaitez: des versions améliorées seront disponibles sur le repo github du projet « geneager ». Ces prochaines versions dépendrons d’autres classes PHP pour le système anti-CRSF.
25/05/2022:
- Modification de la logique.
- Le contenu à insérer avant ou après l’élément est mis en 3e paramètre (type « array ») de la méthode « setElement ».
- $attributList est remplacé par $arrayElement pour éviter toutes confusions.
24/05/2022:
- Suppression du « data-gngLabel » -> remplacé par un tableau « html » contenant les clés « before » et « after »