使用jQuery验证验证自定义方法

时间:2016-11-09 14:20:47

标签: jquery jquery-validate

我想验证我的表单,因为如果代码已经存在于列表中,我就无法输入代码。

<select id="form:choices_values" name="form:choices_values" multiple="true" class="ui-helper-hidden">
  <option value="1" selected="selected">1</option>
</select>

Bellow是primefaces orderlist元素的html。

$.validator.addMethod('codExistss', function (value, element) {
   var lstChoices = document.getElementById('form:choices_values');
   for (i = 0; i &lt; lstChoices.options.length; i++) {
        return value === lstChoices.option[i].value;
   }
}, "The code already exists.");

$(document).ready(function () {
  $('#form').validate({
     rules: {
         'form:inptCode': {
              codExistss: false
         }
     }
  });
});

因此,列表包含值1.如果我在inputText中键入数字1,则应显示错误消息。

为了实现这一点,我添加了一个方法,当这个方法返回false时,我试图验证表单。 我没有太多使用jQuery验证的经验,实际上我只写了几个方法。

arcanist

似乎我的代码不起作用。那么,你能帮助我理解为什么吗?

1 个答案:

答案 0 :(得分:0)

您对所有列表选项都有一个循环:

  for (i = 0; i &lt; lstChoices.options.length; i++) {
        return value === lstChoices.option[i].value;
   }

假设你有超过1个选项,那么只有一次条件会返回true并且你的验证被破坏了。

第二件事是您没有打开自定义函数的规则标志: 您有codExistss: false表示“不通过此规则验证输入”,请将其更改为true。

试试这个:

$.validator.addMethod('codExistss', function (value, element) {

       var lstChoices = document.getElementById('form:choices_values');
       if(lstChoices.options[lstChoices.selectedIndex].value===value) {return false;}
       return true;
       },"The code already exists.");

$(document).ready(function () {
  $('#form').validate({
     rules: {
         'form:inptCode': {
    // Specify that form:inptCodeshould be validated
    // by codExistss rule
              codExistss: true
         }
     }
  });
});
相关问题