I want to validate an input field to be numeric with a variable precision, e.g. 1, 1.2, 1.23, etc. If I was doing it without jQuery, it'd look something like this:
However, in trying to do it with jQuery, I have the following:
...and I am not getting a good grasp of how I should bridge the difference of functionality. Ultimately, I'd like some universal common jQuery validation that I can re-use by calling the same file in multiple places, but it's been slow going. The best I've come up with is creating multiple classes for each instance, and having each class with its own handler function that calls the same common function, passing its proprietary parameter, but that just feels clunky. Any insight would be appreciated, as I am still trying to wrap my head around jQuery. Thanks.
Code:
function validateNum(id, precision){
var regex = /^\d{1,3}\.?\d{precision}$/;
if (document.getElementById(id).value.search(regex) ==-1) {
return false;
} else {
return true;
}
}
<input id = 'numeric' onBlur = 'javascript:validateNum('numeric', 0)'>
<input id = 'money' onBlur = 'javascript:validateNum('money', 2)'>
However, in trying to do it with jQuery, I have the following:
Code:
$(document).ready(function(){
// Validate for 2 decimal for money
jQuery.validator.addMethod("money", function(value, element) {
return this.optional(element) || /^(\d{1,3})(\.\d{2})$/.test(value);
}, "Must be in US currency format 0.99");
<input type=text name=proCompPrice1 class = 'money'