Wednesday, August 19, 2015

Validate no. of characters and their type entered into any input field using Java Script.

Here are I am writing an example how can we make sure that entered input in a filed should be only a 6 Digit number. You can modify it to according to your requirements:

var InputFieldValue = $("#InputFiledID").val();//Bit Jquery :) You can use java script too.

if( InputFieldValue!= '')
    {
var digits = "0123456789";
        var temp;
        if (InputFieldValue.length > 6){
        alert("Entered value cannot be more than 6 Digit Numbers ");
        return false;
        }
        else if(InputFieldValue.length < 6){
        alert("Entered value cannot be less than 6 Digit Numbers ");
        return false;
        }
        else {
for (var i = 0; i < InputFieldValue.length ; i++) {
        temp = InputFieldValue.substring(i, i + 1);
        if (digits.indexOf(temp) == -1) {
        alert("Entered value cannot contain any Character.");
        return false;
        }
        }
        }
     }

On the above code we have provided a string of characters which we want to permit as inputs. In this case we want to validate against numerals.  Then we select each character of input field value and try to find it into our format string, if it does not contain we return vale as false.

This can be extend for checking against any format.

Here is an example how can we extend it. For an input in this format "xx-xx-xx" where 'x' needs to be a number:

if( InputFieldValue != '')
{
var digits = "0123456789";
        var temp;
        if (InputFieldValue.length > 8){
        alert("Entered Value cannot be more than 6 Digit Numbers ");
                return false;
                }
                else if(InputFieldValue.length < 8)
                {
                alert("Entered Value cannot be less than 6 Digit Numbers ");
                return false;
                }
                else {
for (var i = 0; i < InputFieldValue.length; i++) {
            temp =InputFieldValue.substring(i, i + 1);
            if(i==2|| i==5)
            {
            if(temp!='-')
            {
            alert("Entered Value be in xx-xx-xx format. Does not conation - in current values.");
                   return false;
                   }
            }
            else if (digits.indexOf(temp) == -1) {
                alert("Entered Value cannot contain any Character ");
                return false;
            }
            }
             }
            }

On the above code, we are making sure that on 3rd and 5th position its always contain '-'.

Hope it helps someone.


1 comment: