Sunday, March 11, 2012

Advanced jQuery Form validation (5): how to limit the value of an input field to another's

In this example, we will limit the maximal value entered in an input field according to the one entered in another one.
The form has two input fields:
  • The first field is limited between 0 and 100 (limitation defined in the rule range: [0, 100])
  • The second one is limited between 0 and the value entered in the first field.

The range method of the validation plugin enables us to set the minimal and maximal values linked to a given input field. It can be written as a bracket of two values, or as a function that returns a boolean.
Here, we link the maximal value entered in the second input field with the one entered in the first input field (or with the maximal authorized value in the first input field if it is empty).
<form id="myFormId" method="post">
    <label for="fieldOne">Field One</label>
    <input type="text" name="fieldOne" id="fieldOneId" value="" /><br/>
    <label for="fieldTwo">Field Two</label>
       <input type="text" name="fieldTwo" id="fieldTwoId" value="" /><br/>
    <input type="submit" value="Submit" />
</form>
$("#myFormId").validate({
    rules: {
        fieldOne: range: [0, 100],
        fieldTwo:
            range: function() {
                var maxValue = ($("#fieldOneId", "#myFormId").val() == '')? 100: $("#fieldOneId", "#myFormId").val();
                return [0, Math.min(maxValue, 100)];
            }
    }
});


Validation de formulaire jQuery avancée (5) : comment limiter la valeur d'un champ de saisie à celle d'un autre (in French)
Validación de formulario jQuery avanzado (5): cómo limitar el valor de un campo de entrada a la de otro (in Spanish)
Validação de formulário jQuery avançado (5): como limitar o valor de um campo de entrada à doutro (in Portuguese)

No comments:

Post a Comment