IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Validation Coté client


Sujet :

JavaScript

  1. #1
    Membre du Club
    Homme Profil pro
    Inscrit en
    Avril 2012
    Messages
    90
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Avril 2012
    Messages : 90
    Points : 60
    Points
    60
    Par défaut Validation Coté client
    Bonjour, j'aurai besoin de quelques informations concernant la validation coté client d'un formulaire.

    Pour résumer ce que je cherche à faire j'ai un formulaire avec des champs requis et des champs dates (Début et Fin avec Début < Fin) et un input submit.
    La vérification de ces champs requis et des dates fonctionne coté serveur et affiche correctement les messages d'erreur quand les conditions ne sont pas respectées(Je ne mets pas le code pour ne pas surcharger la question mais le formulaire est disons basique).

    On m'a dit que pour une bonne pratique il faut également mettre en place une vérification coté client en utilisant notamment javascript. C'est la que mes problèmes commencent...

    En cherchant j'ai cru comprendre qu'il fallait donc une fonction javascript.

    ex
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    <script type="text/javascript">
        function isValid() {
            // Vérification des champs saisie coté client
            ...
        }
        //  }
    </script>
    Mon problème est que je ne sait pas comment rentré dans cette fonction J'ai tenté un onclick="isValid();" sur l'input submit sans succès.

    Quelqu'un pourrait éclairer ma lanterne?

    Une deuxième question concerne le contenu de la function isValid().
    Doit-elle comprendre des accès aux composants que l'on souhaite vérifié genre "document.getElementByID()"

    Je continu à chercher mais si quelqu'un aurait un peu de temps pour m'en dire un peu plus sur le sujet ou me conseiller des tutos je lui serait reconnaissant.

    Cordialement,
    Christophe.

  2. #2
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 640
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 640
    Points : 66 663
    Points
    66 663
    Billets dans le blog
    1

  3. #3
    Rédacteur/Modérateur

    Avatar de SylvainPV
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    3 375
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 3 375
    Points : 9 944
    Points
    9 944
    Par défaut
    Bonjour,

    Effectivement une bonne pratique est la double-validation, côté client pour la réactivité et pour éviter des requêtes inutiles, et côté serveur pour la sécurité. Il faut d'abord coder et tester la validation côté serveur avant d'ajouter une validation côté client.

    Si tu ne veux pas t'embêter à coder tout toi-même, il y a des bibliothèques JavaScript dédiées à la validation de formulaire : http://jster.net/category/validation

    Si tu veux apprendre, je partage une fonction fait-maison que j'utilise pour la validation des formulaires de mon projet actuel. C'est pas le meilleur code qui soit, mais ça fait le job et c'est plutôt polyvalent :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
     app.checkEmailFormat = function(email){    	var reg = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');
        	return reg.test(email);
        };
     
     
        app.checkDateFormat = function(date){ // VERIFICATION DU FORMAT JJ/MM/AAAA
            var year = parseInt(date.split('/').pop());
            return moment(date,"DD/MM/YYYY").isValid() && year > 1800 && year < 2500;
        };
     
     
        app.checkHourFormat = function(hour){ // VERIFICATION DU FORMAT HH:MM
            return moment(hour,"HH:mm").isValid();
        };
     
     
        app.checkAlphanumericFormat = function(str){
            var reg = new RegExp(/^[a-zA-Z0-9\-\sçàéêôîïûùèë]+$/);
        	return reg.test(str);
        };
     
     
        app.checkAlphanumericPlusFormat = function(str){
            var reg = new RegExp(/^[a-zA-Z0-9\-._\sçàéêôîïûùèë]+$/);
        	if(reg.test(str)){
        		if(str.indexOf("_._") > -1){
        			return false;
        		}
        		else return str.indexOf("_.._") <= -1;
        	}
        	else{
        		return false;
        	}
        };
     
     
        app.checkAlphanumericPlusPointFormat = function(str){
            var reg = new RegExp(/^[a-zA-Z0-9\-._\sçàéêôïîûùèë]+$/);
        	return reg.test(str);
        };
     
     
        app.checkAlphaFormat = function(str){
        	var reg = new RegExp(/^[-\sa-zA-Zçàéêôïîûùèë]+$/);
        	return reg.test(str);
        };
     
     
        app.checkAlphaPlusFormat = function(str){
        	var reg = new RegExp(/^[a-zA-Z\-'\sçàéêôïîûùèë]+$/);
        	return reg.test(str);
        };
     
     
        app.checkNumericFormat = function(str){
            var reg = new RegExp(/^[0-9]+$/);
        	return reg.test(str);
        };
     
     
        app.checkPhoneFormat = function(str){
            return /^0[1-9]([0-9]{8})$/.test(str);
        };
     
     
        app.initFormValidation = function(form, onSubmit, onError){
            $(form).off('submit').on("submit", function(event){
                $(form).find(".to_check:enabled").each(function(i,field){
                    app.checkField(field);
                });
                //on va vérifier si pour les champs renseignés, leur format est correct
                var errorMessage = null,
                	errorField = $(".error_field");
     
     
                if(errorField.size() > 0){
                    errorMessage = app.lang["inscription.formatko"];
                }
     
     
                var listeMandatoryField = $(this).find(".mandatory_field") ;
                for(var i=0; i<listeMandatoryField.length ; i++){
                    var field = listeMandatoryField.eq(i);
                    if(field.attr("type") != "checkbox" && $.trim(field.val()) == ""){
                        errorField = field;
                        errorMessage = app.lang["general.formulaireIncomplet"]; //Il manque un champ obligatoire                    
                        break;
                    } else if(field.attr("type") == "checkbox" && field.is(":checked") === false){
                        errorField = field;
                        errorMessage = app.lang["inscription.validConditions"];
                        break;
                    }
                }
     
     
                if(errorMessage != null){
                    app.notifications.putError(errorMessage);
                    if(isFunction(onError)){ onError(errorField, errorMessage); }
                } else{
                    event.stopPropagation();
                    onSubmit($(form));
                }
                return false;
            }).on("blur change", ".to_check", function(event){
                 //timeout pour le JIRA 395
                 setTimeout(function(){ app.checkField(event.target) },100);
            });
        };
     
     
        app.checkField = function(elt){
            var obj = $(elt || this);
            var error = null;
            var isEmpty = $.trim(obj.val()) === "";
            if(isEmpty){
                if(obj.hasClass("mandatory_field")){
                    error = app.lang["inscription.champOblig"];
                } //else -> no error
            }
            else if(obj.hasClass("email") && app.checkEmailFormat(obj.val()) !== true){
                error = app.lang["inscription.formatEmailko"];
            }
            else if(obj.hasClass("phone") && app.checkPhoneFormat(obj.val()) !== true){
                error = app.lang["inscription.formatPhoneko"];
            }
            else if(obj.hasClass("date") && !isEmpty && app.checkDateFormat(obj.val()) !== true){
                error = app.lang["inscription.formatDateko"];
            }
            else if(obj.hasClass("time") && !isEmpty && app.checkHourFormat(obj.val()) !== true){
                error = app.lang["inscription.formatTimeko"];
            }
            else if(obj.hasClass("alphanumeric") && app.checkAlphanumericFormat(obj.val()) !== true){
                error = app.lang["inscription.formatReponseko"];
            }
            else if(obj.hasClass("alphanumericplus") && app.checkAlphanumericPlusFormat(obj.val()) !== true){
                error = app.lang["inscription.formatReponsePlusko"];
            }
            else if(obj.hasClass("alpha") && app.checkAlphaFormat(obj.val()) !== true){
                error = app.lang["inscription.formatAlphako"];
            }
            else if(obj.hasClass("alphaplus") && app.checkAlphaPlusFormat(obj.val()) !== true){
                error = app.lang["inscription.formatFormko"];
            }
            else if(obj.hasClass("alphanumericpluspoint") && app.checkAlphanumericPlusPointFormat(obj.val()) !== true){
                error = app.lang["inscription.formatFormko"];
            }
            else if(obj.hasClass("numeric") && app.checkNumericFormat(obj.val()) !== true){
                error = app.lang["inscription.formatNumericko"];
            }
            else if(obj.hasClass("pwd")){
                var pwd = obj.val() ;
                if($.trim(pwd) === ""){
                    error = app.lang["inscription.mdpOblig"];
                }
                else if(pwd.length < 8){
                    error = app.lang["inscription.formatMdpko"];
                }
                else{
                	obj.removeClass("error_field");
                }
     
     
                var pwdConf = $("#password_confirm");
                if($.trim(pwdConf.val()) != ""){
                	if(pwd != pwdConf.val()){
                		error = app.lang["inscription.mdpIncoherent"];
                	} else if(pwdConf.hasClass("error_field")){
                        app.checkField(pwdConf);
                	}
                }
            }
            else if(obj.hasClass("pwd_conf")){
                var pwdConf = obj.val();
                var pwd = $("#password");
     
     
                if(pwd.val() != pwdConf){
                    error = app.lang["inscription.mdpIncoherent"];
                } else if(pwd.hasClass("error_field")){
                    app.checkField(pwd);
                }
                else{
                	obj.removeClass("error_field");
                }
            }
     
     
            if(obj.hasClass("date")){
                obj = obj.next(".icon-calendar");
            }
            obj.next().next("div.error").remove();
            obj.next("img.check_error").remove();
            obj.toggleClass("error_field", error != null);
            if(error){
                obj.after("<img class='check_error' src='img/check-cancel.png' align='absmiddle'/><div class='error'><p>"+error+"</p></div>");
            } else if(!isEmpty){
                obj.after("<img class='check_error' src='img/check-valid.png' align='absmiddle'/>");
            }
            if(obj.closest(".jspContainer").length > 0){
                obj.closest(".jspContainer").parent().makeScrollable();
            }
        };

  4. #4
    Membre du Club
    Homme Profil pro
    Inscrit en
    Avril 2012
    Messages
    90
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Avril 2012
    Messages : 90
    Points : 60
    Points
    60
    Par défaut Re
    Merci pour ces liens et explications.

    Mon dernier problème est que je n'arrive pas à entrer dans ma fonction de validation voici comment je la declare

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    <script type="text/javascript">
        function IsValid() {
            var AllIsOk = 0;
     
            if (document.getElementById('datepicker1').value > document.getElementById('datepicker2').value) { AllIsOk++; }
     
            return (AllIsOk == 0);
        }
    </script>
    (Je ne sais pas si le test est correctement écrit pour l'instant.


    Voici comment je déclare mon formulaire

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
        @using (Html.BeginForm("InsertAbsence", "Absence", FormMethod.Post, new { ID = "insertAbsenceForm", onsubmit = "return IsValid()" }))
        { 
     
    [.......]
     
            <div>
                <input class="button_submit" type="submit" value="Ajouter" />
            </div>  
        }
    concernant le paramètre onsubmit sur le html.beginForm j'ai aussi essayé avec onsubmit = "return IsValid();" mais je n'entre tjs pas dans ma fonction.

  5. #5
    Membre du Club
    Homme Profil pro
    Inscrit en
    Avril 2012
    Messages
    90
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Avril 2012
    Messages : 90
    Points : 60
    Points
    60
    Par défaut
    en fait c'est bon je passais bien dans la fonction. Je vous remercie pour vos reponses.

    Cordialement.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Struts 2 validation coté client
    Par aya02 dans le forum Struts 2
    Réponses: 0
    Dernier message: 18/04/2010, 02h39
  2. Réponses: 2
    Dernier message: 24/02/2010, 09h59
  3. struts validator coté client, alertbox sans message
    Par jayjaypg22 dans le forum Struts 1
    Réponses: 2
    Dernier message: 23/02/2010, 11h01
  4. pb validation coté client
    Par Melaba dans le forum Struts 1
    Réponses: 1
    Dernier message: 07/08/2008, 16h59
  5. [Validator]Validation coté client
    Par trihanhcie dans le forum ASP.NET
    Réponses: 2
    Dernier message: 26/11/2007, 16h49

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo