Thursday, November 15, 2012

JavaScript functions for realtime validation


These are the functions you need to validate input fields.
You can add these functions to a common JavaScript file and include that to whole website.

Block users to type other characters in numeric fields.


  1. $(document).ready(function() {      
  2.       
  3.     $('.numeric-only').keypress(function (e){  
  4.           if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){  
  5.             return false;  
  6.           }  
  7.     });  
  8.   
  9. });  
Usage:
  1.  <input type="text" name="age" class="numeric-only" maxlength="3"/>  
Demo:

Age: 

 

Capitalize text when typing.

This will capitalize first letter in every word in the text field.
  1. $(document).ready(function() {      
  2.       
  3.     $('.capitalize').keyup(function(evt){  
  4.         var text = $(this).val();  
  5.         $(this).val(text.replace(/^(.)|\s(.)/g, function(data){ return data.toUpperCase( ); }));  
  6.     });  
  7.   
  8. });  
Usage:
  1.  <input type="text" name="fullname" class="capitalize" />  
Demo:

Full Name: 

Alpha only

This will only allow alpha characters when typing.
  1. $(document).ready(function() {  
  2.     $('.alpha-only').keyup(function (e){  
  3.                     
  4.             var text = $(this).val();  
  5.             txt=text.replace(/[^a-zA-Z]/g, '');  
  6.             $(this).val(txt);       
  7.   
  8.     });  
  9.   
  10. });  

Usage:
  1.  <input type="text" name="username" class="alpha-only" />  
Demo:

Username: 

Alpha numeric only

This will only allow alpha and numeric characters when typing.
  1. $(document).ready(function() {  
  2.     $('.alpha-numeric-only').keyup(function (e){  
  3.                  
  4.         var text = $(this).val();  
  5.         txt=text.replace(/[^a-zA-Z0-9]/g, '');  
  6.         $(this).val(txt);     
  7.     
  8.     });  
  9. });  
Usage:
  1.  <input type="text" name="displayname" class="alpha-numeric-only" />  
Demo:

Display Name: 

Alpha numeric space

This will only allow alpha, numeric and space characters when typing.
  1.  $(document).ready(function() {  
  2.     $('.alpha-numeric-space').keyup(function (e){  
  3.                  
  4.         var text = $(this).val();  
  5.         txt=text.replace(/[^a-zA-Z 0-9\s]/g, '');  
  6.         $(this).val(txt);     
  7.     
  8.     });  
  9. });  
Usage:
  1.  <input type="text" name="nickname" class="alpha-numeric-space" />  
Demo:

Nickname: 

1 comment: