Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing function vars - converting JavaScript to jQuery

Status
Not open for further replies.

JBellTek

Programmer
Jun 11, 2009
29
US
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:

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'
...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.
 
jmeckley:
Thank you. I'd looked for a jQuery forum, but I guess somehow I missed it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top