JavaScript

jQuery useful validation functions

Here i will share some useful jQuery validation properties and functions with you, like counting the length of an element, allowing alphanumeric and numbers only values to an input element.

1- Count length of an input box value ?

$(id).val().length

jQuery length property is use to calculate the total element in the jQuery object.

Example

function checklength(id){

var no=$(id).val.length;

alert(no);

}
<input type="text" id="name" onBlur="checklength(this.id)" />

when you focus out of the input box checklength() function calculate the length of your input box value and retrun you in alert box.

 

2: Check alphanumeric value

function isAlphaNumeric(value){
var expression=/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+[0-9a-z]+$/i;
 if(value.match(expression)){
 alert("Value is alphanumeric");
 return true;
 }
else{
 alert("Value is not alphanumeric");
 return false;
 }

}
<input type="text" id="name" onBlur="isAlphaNumeric(this.value)" />

when you focus out of the input box, the above function match your input box value with the defined regular expression “/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+[0-9a-z]+$/i;”. if it will match with it, it return you true otherwise alert box.

 

3: Allow numbers only to an input field

function chk() { 
var key=window.event.keyCode; 
if(key>57 || key<48) { 
window.event.returnValue=false; 
alert("Enter numbers only");
 }
 }
<input type="text" id="name" onKeypress="chk()" />

key 57 is the code of number 9 and key 48 is the code of number 0, so it check that the press key is greater than 9 and less than 0, it returns a alert box with the defined message.

4: How to check blank space

function chkspc()
{
var key=window.event.keyCode;
if(key==32)
{
window.event.returnValue=false;
alert("Space not allowed");
}
}

key 32 is the code of space key , so it check that the press key code is equal to 32, it returns a alert box with the defined message.

<input type="text" id="name" onKeypress="chkspc()" />

 

So Guys if feel any problem with these functions, you can leave it on comment. I will try to reply you and thank you to read our blog. Keep visiting

Please follow and like us:

About Viren-Dra Yadav

Tech Enthusiast | Open Source Lover | WordPress Explorer | Mad for Speed | DevOps Engineer | AgriTech
View all posts by Viren-Dra Yadav →

Leave a Reply

Your email address will not be published. Required fields are marked *