Validation d’un formulaire côté client

Il est possible de faire une validation avant l’envoi d’un formulaire sur le serveur via le naviguateur

Il existe un plugin jquery nommé jqueryvalidation qui permet de faire ce genre de chose

un exemple simple sur la notion de “required”

<html>
<head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.min.js"></script>

        <script>
        $().ready(function() {
                $("#commentForm").validate({
                submitHandler: function() { alert("submitted!"); }
                })
        });
        </script>

</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
        <fieldset>
                <legend>Please provide your name, email address (won't be published) and a comment</legend>
                <p>
                        <label for="cname">Name (required, at least 2 characters)</label>
                        <input id="cname" name="name" minlength="2" type="text" required />
                <p>
                        <label for="cemail">E-Mail (required)</label>
                        <input id="cemail" type="email" name="email" required />
                </p>
                <p>
                        <label for="curl">URL (optional)</label>
                        <input id="curl" type="url" name="url" />
                </p>
                <p>
                        <label for="ccomment">Your comment (required)</label>
                        <textarea id="ccomment" name="comment" required></textarea>
                </p>
                <p>
                        <input class="submit" type="submit" value="Submit"/>
                </p>
        </fieldset>
</form>
</body>
</html>

le message “submitted!” n’apparait qu’une fois que tout les élements sont validés

Il est possible de mettre en place:

  • des règles spécifiques
  • des messages spécifiques

il faut rajouter des feuilles de styles pour avoir des messages plus lisibles

un exemple intégrant des règles propres

<html>
<head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.min.js"></script>

        <script>
        $.validator.setDefaults({
                submitHandler: function() { alert("submitted!"); }
        });

        $().ready(function() {
                // validate signup form on keyup and submit
                $("#signupForm").validate({
                        rules: {
                                firstname: "required",
                                lastname: "required",
                                username: {
                                        required: true,
                                        minlength: 2
                                },
                                password: {
                                        required: true,
                                        minlength: 5
                                },
                                confirm_password: {
                                        required: true,
                                        minlength: 5,
                                        equalTo: "#password"
                                },
                                email: {
                                        required: true,
                                        email: true
                                },
                                topic: {
                                        required: "#newsletter:checked",
                                        minlength: 2
                                },
                                agree: "required"
                        },
                        messages: {
                                firstname: "Please enter your firstname",
                                lastname: "Please enter your lastname",
                                username: {
                                        required: "Please enter a username",
                                        minlength: "Your username must consist of at least 2 characters"
                                },
                                password: {
                                        required: "Please provide a password",
                                        minlength: "Your password must be at least 5 characters long"
                                },
                                confirm_password: {
                                        required: "Please provide a password",
                                        minlength: "Your password must be at least 5 characters long",
                                        equalTo: "Please enter the same password as above"
                                },
                                email: "Please enter a valid email address",
                                agree: "Please accept our policy"
                        }
                });

                // propose username by combining first- and lastname
                $("#username").focus(function() {
                        var firstname = $("#firstname").val();
                        var lastname = $("#lastname").val();
                        if(firstname && lastname && !this.value) {
                                this.value = firstname + "." + lastname;
                        }
                });

        });
        </script>

</head>
<body>

<form class="cmxform" id="signupForm" method="get" action="">
        <fieldset>
                <legend>Validating a complete form</legend>
                <p>
                        <label for="firstname">Firstname</label>
                        <input id="firstname" name="firstname" type="text" />
                </p>
                <p>
                        <label for="lastname">Lastname</label>
                        <input id="lastname" name="lastname" type="text" />
                </p>
                <p>
                        <label for="username">Username</label>
                        <input id="username" name="username" type="text" />
                </p>
                <p>
                        <label for="password">Password</label>
                        <input id="password" name="password" type="password" />
                </p>
                <p>
                        <label for="confirm_password">Confirm password</label>
                        <input id="confirm_password" name="confirm_password" type="password" />
                </p>
                <p>
                        <label for="email">Email</label>
                        <input id="email" name="email" type="email" />
                </p>
                <p>
                        <label for="agree">Please agree to our policy</label>
                        <input type="checkbox" class="checkbox" id="agree" name="agree" />
                </p>
                <p>
                        <label for="newsletter">I'd like to receive the newsletter</label>
                        <input type="checkbox" class="checkbox" id="newsletter" name="newsletter" />
                </p>
                <fieldset id="newsletter_topics">
                        <legend>Topics (select at least two) - note: would be hidden when newsletter isn't selected, but is visible here for the demo</legend>
                        <label for="topic_marketflash">
                                <input type="checkbox" id="topic_marketflash" value="marketflash" name="topic" />
                                Marketflash
                        </label>
                        <label for="topic_fuzz">
                                <input type="checkbox" id="topic_fuzz" value="fuzz" name="topic" />
                                Latest fuzz
                        </label>
                        <label for="topic_digester">
                                <input type="checkbox" id="topic_digester" value="digester" name="topic" />
                                Mailing list digester
                        </label>
                        <label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
                </fieldset>
                <p>
                        <input class="submit" type="submit" value="Submit"/>
                </p>
        </fieldset>
</form>
</body>
</html>

les principales règles sont:

  • required – Makes the element required.
  • remote – Requests a resource to check the element for validity.
  • minlength – Makes the element require a given minimum length.
  • maxlength – Makes the element require a given maxmimum length.
  • rangelength – Makes the element require a given value range.
  • min – Makes the element require a given minimum.
  • max – Makes the element require a given maximum.
  • range – Makes the element require a given value range.
  • email – Makes the element require a valid email
  • url – Makes the element require a valid url
  • date – Makes the element require a date.
  • dateISO – Makes the element require a ISO date.
  • number – Makes the element require a decimal number.
  • digits – Makes the element require digits only.
  • creditcard – Makes the element require a creditcard number.
  • equalTo – Requires the element to be the same as another one

et on peut en rajouter avec l’utilisation par exemple d’expression régulière

création de la règle regex

jQuery.validator.addMethod(
  "regex",
   function(value, element, regexp) {
       if (regexp.constructor != RegExp)
          regexp = new RegExp(regexp);
       else if (regexp.global)
          regexp.lastIndex = 0;
          return this.optional(element) || regexp.test(value);
   },"erreur expression reguliere"
);

utilisation de la règle regex

"montelephone": {
    "required": true,
    "regex": /^(\+33\.|0)[0-9]{9}$/
}

Note

pour avoir des messages en français il suffit d’intégrer le fichier messages_fr.js dans la page html