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
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
2 Comments
don't forget to always use server side checking... because client side is checking always easy to bypass.. :)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:
Comments
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
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
/\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!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