views:

82

answers:

4

How to do numeric validation using JQuery. I have to validate my price field using JQuery. any body knows please share your knowledge with me :(

+2  A: 

use jquery validation plugin

http://www.bassistance.de/jquery-plugins/jquery-plugin-validation/

It contains all the validations like, require, format, size, range, value

Starx
+4  A: 

If your looking for form validation, you can look into the validation plugin: http://docs.jquery.com/Plugins/Validation

However if you just want some sample code, it could be as simple as this:

$(function() {
  $('ref-to-input').blur(function() {
    if($(this).val().match(/[^\d]/)) {
      // invalid chars detected
    }
  });
});

you could also filter your input to only allow numeric characters:

$(function() {
  $('ref-to-input').keyup(function() {
    $(this).val($(this).val().replace(/[^\d]/, ''));
  });
});

Edit: don't forget to always use server side checking

Ben Rowe
+1 for `don't forget to always use server side checking`... because client side is checking always easy to bypass.. :)
Reigel
@Reigel +1 for client side checking being easy to bypass. It is absolutely trivial so ALWAYS check on the server side also.
Darko Z
+1  A: 
function IsNumeric(sText){
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

USE:

if ( IsNumeric(my_number) )
//do some here...
aSeptik
Isn't it just a lot easier (and shorter) to use regular expressions?
Kimmo Puputti
Well, not quite... That regex wouldn't catch e.g. '3.1' or '3.145'. But anyways, your answer is just an ugly way to go around using a simple regex to check for numeric input.
Kimmo Puputti
yes, you are right for the regex it should be like this `/\d[\d.,]*/` but i'm still of my opinion that depend on what the OP is going to do since there are a lot of price format, you need to take care of many circumstance!
aSeptik