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 :(
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
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/
use jquery validation plugin
http://www.bassistance.de/jquery-plugins/jquery-plugin-validation/
It contains all the validations like, require, format, size, range, value
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...
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
精彩评论