JavaScript : Advanced Form Management
Contents ]
Mikael Le Moal

Mandatory Numerical Field

If the field is mandatory, the numerical value will need to be verified in two steps, otherwise, the second step will suffice. The first step makes sure that a value has been entered. This is the job of the function nonVide():

17: function nonVide(mt) {
18:    if (mt.value.length<1) {
19:       return false;
20:    }
21:    else {
22:       return true;
23:    }
24: }

The role of this function is to establish that the argument given contains something. If this is not the case, the value of length is smaller than 1 and the function returns false, otherwise, it returns true.

Keep track of your visitors. Most sites display an asterisk (*) after mandatory fields in a form.

The second step, which can be used alone for a non-mandatory numerical field, uses the function verifNb to verify that the decimal part does not contain more than one digit. It receives two arguments: the first is the form field to check and the second is the number of decimal places allowed:

26: function verifNb(mt,dec) {
27:    if (mt.value == "") {
28:      return true;
29:    }
30:
31:    if (isNaN(mt.value)) {
32:       return false;
33:    }
34:    else {
35:      if (mt.value.indexOf('.') == -1) {
36:          return true;
37:      }
38:      else {
39:        dectext = mt.value.substring(mt.value.indexOf('.')+1, mt.value.length);
40:        if (dectext.length > dec)  {
41:           return false;
42:        }
43:        else {
44:           return true;
45:        }
46:      }
47:    }
48: }

For situations where the field is not mandatory, we check whether or not it is empty (lines 27 to 29). If this is the case, it is still considered valid. In the case of a mandatory field, we also need to use the previously described function nonVide. We then verify that the value is actually a number (lines 31 to 33). To do this, we use the JavaScript function isNaN().

Now we want to know if the value contains decimals (lines 35 to 37). We just need to look for a decimal point in the value. If there is one, we proceed further. Otherwise, the field is already valid. The last check is to make sure that the number of decimal places does not exceed the maximum limit (lines 38 to 46). For this purpose we store all the digits that follow the decimal point in a variable named dectext. The length of this variable gives us the number of decimal places, which we finally compare with the second argument passed to the function which determines whether or not the field value (line 40) is validated.



  1   2   3   4   5