开发者

comparing variables for validate addMethod

Ive been struggling with this all day, been close a couple times but nothing seems to work exactly.

I have a text input <input type="text" name="USA_sub" id="USA_sub" /> and after that an 开发者_运维技巧input <input type="text" name="FirstName" id="FirstName" /> I need to make sure (create a validation rule) that states "#FirstName" 's value must be contained in "#USA_sub" 's value.

I keep getting the error "$(sig).contains is not a function" with this:

$.validator.addMethod("FNESig", function (value, element) {
    var firstname = $("#FirstName").val();
    var sig = $("#USA_sub").val();

    if ($(sig).contains(firstname)) {
        return true;
    } else return false;
}, "Your First Name must be in your Electronic Signature.");

thx Kane


Instead of this ($().contains() isn't a method...and you have a string, not a selector for a jQuery object, no need to wrap anything):

if ($(sig).contains(firstname)) {
    return true;
    } else return false;

You can just use string.indexOf(), like this:

return sig.indexOf(firstname) != -1; //-1 would mean it wasn't found

As a side note, since you're returning the same result as the condition, just return it, in other words this:

if(someCondition) {
  return true;
} else {
  return false;
}

Can just be:

return someCondition;


Try this:

if (sig.indexOf(firstname) >= 0) {
    return true;
} else return false;


contains method in jQuery can only be applied to DOM elements. You may want to use indexOf javascript method instead. It will search for an occurrence of the specified value in a string

$.validator.addMethod("FNESig", function (value, element) {
    var firstname = $("#FirstName").val();
    var sig = $("#USA_sub").val();

    // means: does sig contains firstname?
    return (sig.indexOf(firstname) !== -1);

}, "Your First Name must be in your Electronic Signature.");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜