添加新的验证方法jQuery无法正常工作

时间:2017-10-30 08:57:07

标签: jquery jquery-validate linkedin

我想验证LinkedIn个人资料网址。这不是必填字段,但是当用户输入数据时,它应该只允许正则表达式格式。当它不匹配时,它应该将消息显示为无效。我试过这样但它甚至没有触发。我该如何调试呢?

jQuery.validator.addMethod("linkedinUrl", function(value, element) {
  return this.optional(element) || /(ftp|http|https):\/\/?(?:www\.)?linkedin.com(\w+:{0,1}\w*@)?(\S+)(:([0-9])+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(value);
});

$(function() {
  $("#Add_Staff_Form").validate({
    rules: {
      linkedin {
        required: true;
        linkedinUrl: true;
      }
    },
    messages: {
      linkedin {
        required: "Please specify the correct linkedin url"
      }
    },
    ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input'
  });
});
<div class="col-md-4">
  <label class="control-label">Linkedin</label>
  <input type="text" id="linkedin" name="linkedin" class="form-control" value="" />
</div>   

1 个答案:

答案 0 :(得分:0)

这将有效:

<script>
    jQuery.validator.addMethod("linkedinUrl", function(value, element) {
    return this.optional(element) || /(ftp|http|https):\/\/?(?:www\.)?linkedin.com(\w+:{0,1}\w*@)?(\S+)(:([0-9])+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(value); }, "Please enter valid linkedin url!" );

    $(function () {
        $("#Add_Staff_Form").validate({
            rules: {
                linkedin:"linkedinUrl",
            },
            ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input'
        });
    });
</script>

在html中添加:

<div class="col-md-4">
    <label  class="control-label">Linkedin</label>
    <input type="text" id="linkedin" name="linkedin" class="form-control linkedinUrl" value=""   />
</div>