Pure JavaScript Functions for Validation


In this article I am going to cover some JavaScript functions which are written in pure JavaScript. These function are used for validate the user’s input at client side. These are ready to use functions, so you can use them and save your time also you can modify these for your purpose.

1. To Get Only Numbers From User
This function is very useful to get only numbers from the user. It will prevent the user to input any character other then number.

function numbersOnly(e, decimal) {
    var key;
    var keychar;

    if (window.event) {
        key = window.event.keyCode;
    }
    else if (e) {
        key = e.which;
    }
    else {
        return true;
    }
    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
        return true;
    }
    else if ((("0123456789").indexOf(keychar) > -1)) {
        return true;
    }
    else if (decimal && (keychar == ".")) { 
        return true;
    }
    else
        return false;
}

Usage:

<input type="text" name="number" onkeypress="return numbersOnly(event,false)" />

You can use numbersOnly() function for float values by passing second parameter(decimal) to true like below:

<input type="text" name="decimal" onkeypress="return numbersOnly(event,true)" />

2. Another Function to check Float value
This function is used to check if the user entered float value or not.

function isFloat(value){
    if(isNaN(value)){
        return false;
    } else {
        if(parseFloat(value)) {
	    return true;
	} else {
	    return false;
	}
    }
}

Usage:

 
if(isFloat(value)){
    alert('valid value');
}else{
    alert('invalid value');
}

3. Show Limit Counter on User’s Input
This function counts the input from user and shows the counter of remaining character. It can trim every character after the limit even you paste the content on the field.

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

Usage:
first parameter for user input field, second parameter is for countdown field and third one is for the limit of characters.

<textarea rows="5" cols="50" onKeyup="limitText(this.form.description,this.form.countdown,140);" onBlur="limitText(this.form.description,this.form.countdown,140);" name="description"  ></textarea>
<input type="text" name="countdown" disabled size="5" /> characters

4. To Check User’s Input in Various ways
This function is used to check user’s input for various validation. like isNumber, isFloat, isPhone etc.

function checkString(str, strValidChars){
	var strChar;
	var blnResult = true;
	for (i = 0; i < str.length && blnResult == true; i++)
	{
		strChar = str.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

Usage:

checkString(input, "+-()0123456789 "); // for phone
checkString(input, ".0123456789"); // for Float
checkString(input, "0123456789"); // for Number

5. To Check if Value Exists in an Array
This function is used to check if the value is exists in an array. It works exactly same as in_array in PHP.

function in_array (needle, haystack, argStrict) {
	var key = '', strict = !!argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	}
	return false;
}

Usage:
Following will alert true because ‘NT’ is exists in the array.

var os = ["Mac", "NT", "Irix", "Linux"];
alert(in_array('NT', os));

6. Check in Array and Return key
This function will check the value if it is in array and return its key.

function in_array_returnKey (needle, haystack, argStrict) {
	var key = '', strict = !!argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return key;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return key;
			}
		}
	}
	return -1;
}

Usage:
Following will alert 1 because ‘NT’ is exists in the array and its position is 1.

var os = ["Mac", "NT", "Irix", "Linux"];
alert(in_array_returnKey('NT', os));

7. To Compare 2 Array
Following function used to compares first array against second array and returns the difference.

function arr_diff(a1, a2){
	var a=new Array();
	var diff=new Array();
	var returnData;
	a=a1;
	for(var i=0;i<a2.length;i++){
		returnData=in_array_returnKey(a2[i],a);
		if(returnData!=-1){
			delete a[returnData];
		}
	}
	for(var k in a){
		diff.push(a[k]);
	}
	return diff;
}

Usage:

var os = ["Mac", "NT", "Irix", "Linux"];
var mix = ["Mac", "Android","IOS"];
alert(arr_diff(os, mix).join(',')); // ["NT","Irix","Linux"]

LIVE DEMO

JavaScript Functions for Validation
JavaScript Functions for Validation