3

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 :(

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for don't forget to always use server side checking... because client side is checking always easy to bypass.. :)
@Reigel +1 for client side checking being easy to bypass. It is absolutely trivial so ALWAYS check on the server side also.
1

This is also good for form validation:

http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

Theres an example:

http://www.position-relative.net/creation/formValidator/

Comments

1

use jquery validation plugin

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

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

Comments

1
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...

3 Comments

Isn't it just a lot easier (and shorter) to use regular expressions?
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.
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!
0

Just need to apply this method in Jquery and you can validate your textbox to just accept number only.

function IsNumberKeyWithoutDecimal(element) {    
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp); 
}

Please see working demo here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.