Skip to content
Alexandre FILLATRE edited this page Jul 17, 2014 · 1 revision

Simple validation

This page explains how to validate a field when an event is triggered (form submission in this case)

Code

<html>
    <head>
        <title>JSV Documentation</title>
    <head>
    <body>
        <form action="/send" method="POST" id="myForm">
            <div>
                <label for="firstname">Firstname: </label>
                <input type="text" name="firstname" />
            </div>
            <div>
                <input type="submit" value="Send" />
            </div>
        </form>

        <!-- Loads the validation API -->
        <script type="text/javascript" src="jsv.js"></script>

        <!-- Here you will instantiate the validator and define your validation rules -->
        <script type="text/javascript">
            jsValidator = new JSValidator('myForm',
                new Array(
                    new JSValidator.Rule('firstname', 'NotNull', {'message': 'Firstname should not be empty'})
                )
            );

            jsValidator.bindValidationToElement("myForm", "submit", true)
                .bindFields(jsValidator.getFields());
        </script>
    </body>
</html>

Explanations

Rules

The first thing to know about the validation, is that is works with rules. A rule defines which element should be validated, which constraint should be used, and optionally which configuration should be applied. Take a look at the following example :

new JSValidator.Rule('firstname', 'NotNull', {'message': 'Firstname should not be empty'})

Here, we create a rule to validate the HTML input named firstname. This validation will test if the input content is not null nor empty. If the validation fails, then a 'message' may be displayed (the message will only be displayed if we add the right element in our page - more informations about that later in this page).

Validator

A validator not only takes an array of rules upon construction, but the id of the form you want to validate as well. This allows you to have multiple validators in the same page (if you have multiple forms).

Trigger a validation

Once you have you validator with its rules, you have to define when you want the validation to take place. In order to do that, we'll define an trigger element, an event, and a validation scope (all the fields, or some fields in particular)

jsValidator.bindValidationToElement("myForm", "submit", true)
                .bindFields(jsValidator.getFields());

In this case, we will trigger the validation when the form with id myForm will fire the submit event (i.e. when the form is submitted). The validation will be trigger for all the fields in the form.