简体   繁体   中英

jQuery Validation Engine: Trouble Creating a Custom Function

I've tried both the custom[function_name] and funcCall[methodName] methods listed the the documentation and I can't seem to get either to work.

my custom function looks like this:

function einTest(field, rules, i, options) {
        if (field != null) {
            var x = field.toString();
            if (x.length != 5) {
                return options.allrules.ein.alertText2;
            }
        }
        else {
            return options.allrules.ein.alertText;
        }
    }

and I've created the following in the vaildationEngine-en.js file:

"ein": {
                "alertText": "Not a number.",
                "alertText2": "Must be a 5 digit number."
    },

and I'm trying to use it on the following html field:

<tr>
<td><b>Associate Number (EIN):</b></td>
<td><input type="text" id="EIN" name="EIN" class="validate[required,funcCall[einTest]]" data-prompt-position="inline" /></td>
</tr>

but nothing seems to work... the einTest function is not firing.

Any clues?

jsFiddle Demo

More than likely you were not properly exposing the function. The function needs to be scoped to be called in the global scope. "Validates a field using a third party function call" documentation , basically it means it looks for it to be scoped alongside window .

So the first thing to do is make sure your function is exposed.

window.einTest = function(field, rules, i, options) {

The next thing to keep in mind is that the field is actually the jquery object wrapping the element. So in order to look things like its value or existence, you should use field.val()

if (IsNumeric(field.val())) {

helper function

//source: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input)
{
 return (input - 0) == input && (input+'').replace(/^\s+|\s+$/g, "").length > 0;
}

This is the end result,

html

<p>Enter text in the input and then focus out to see the validation at work.</p>
<b>Associate Number (EIN):</b><br>
<form>
<input type="text" id="EIN" name="EIN" class="validate[required,funcCall[einTest]]" data-prompt-position="inline" />
</form>

js

window.einTest = function(field, rules, i, options) {
 if (IsNumeric(field.val())) {
  var x = field.val();
  if (x.length != 5) {
   return options.allrules.ein.alertText2;
  }
 }
 else {
  return options.allrules.ein.alertText;
 }
};

function IsNumeric(input)
{
 return (input - 0) == input && (input+'').replace(/^\s+|\s+$/g, "").length > 0;
}
//plus library initialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM