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.


$(document).ready(function() {    
    
    $('.numeric-only').keypress(function (e){
          if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
            return false;
          }
    });

});
Usage:
 <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.
$(document).ready(function() {    
    
    $('.capitalize').keyup(function(evt){
        var text = $(this).val();
        $(this).val(text.replace(/^(.)|\s(.)/g, function(data){ return data.toUpperCase( ); }));
    });

});
Usage:
 <input type="text" name="fullname" class="capitalize" />
Demo:

Full Name:

Alpha only

This will only allow alpha characters when typing.
$(document).ready(function() {
    $('.alpha-only').keyup(function (e){
                  
            var text = $(this).val();
            txt=text.replace(/[^a-zA-Z]/g, '');
            $(this).val(txt);     

    });

});

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

Username:

Alpha numeric only

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

Nickname:

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete