Posted By

BrunoDeBarros on 01/07/11


Tagged

javascript jquery validation numeric


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

BrunoDeBarros
AllKnightAccess
hobbyman
jirimelcak


Force an input to be numeric with jQuery


 / Published in: JavaScript
 

URL: http://terraduo.com

This tiny jQuery plug in forces a user to enter only numeric values on an input field by silently removing non-numeric values as they're entered. (Caution: Never rely on client-side validation; use server-side validation as well)

  1. (function ($) {
  2. $.fn.forceNumeric = function () {
  3. return this.each(function () {
  4.  
  5. $(this).keyup(function() {
  6. if (!/^[0-9]+$/.test($(this).val())) {
  7. $(this).val($(this).val().replace(/[^0-9]/g, ''));
  8. }
  9. });
  10. });
  11. };
  12. })(jQuery);
  13.  
  14. // Usage example: $('input.numeric').forceNumeric();

Report this snippet  

You need to login to post a comment.