Validate Numeric value with negative and decimals using Javascript


How to validate Numeric value with negative and decimals using Javascript

The below script shows how to validate a value to be Numeric or decimal with negative value. It will not allow the user to enter any other special characters.
Allows negative and non negative decimal values.



//Validate Numeric value (Allows negative value)
//-------------------------------------------------
function allowNegativeNumber(e) {
var charCode = (e.which) ? e.which : event.keyCode
if (charCode > 31 && (charCode < 45 || charCode > 57) || charCode == 46) {
return false;
}
return true;
}


//Validate Numeric value with negative and decimals
//-------------------------------------------------
function allowNegativeDecimalNumber(e) {
var charCode = (e.which) ? e.which : event.keyCode
if (charCode > 31 && (charCode < 45 || charCode > 57)) {
return false;
}
return true;
}


Comments

Author: Phagu Mahato08 Feb 2014 Member Level: Gold   Points : 5

This JavaScript function you can all in onkeypress event of the textbox and it will validate the user entered value in client side.

function allowNegativeNumber(e) 
{
var charCode = (e.which) ? e.which : event.keyCode
if (charCode > 31 && (charCode < 45 || charCode > 57 )) {
return false;
}
return true;

}
Jquery Validation
$(document).ready(function() {
$("#formID").validate({
rules: {
field_name: {
numericOnly:true
}
}
});
});

$.validator.addMethod('numericOnly', function (value) {
return /[0-9 ]/.test(value);
}, 'Please only enter numeric values (0-9)');



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: