jQuery 动态表单验证

jQuery Validation on dynamic form

我正在开发一个在动态表单上使用 jquery 验证的旧版应用程序。现在我试图将每个 textarea 输入的名称传递给验证但不起作用或者我做错了。我想要验证中的 fieldName 变量(见下文)。

<form class="comment_form" id="update_comment">
  @foreach($user as $key => user)
   <textarea class="form-control" name="comment[$key]"></textarea>
  @endforeach
</form>

<script>
 var $fieldName;
    $.validator.addMethod("allowedChars", function (value) {
        var reg = /^[A-Za-z0-9 _@./*!'"#&+-]*$/;
        return reg.test(value);
    });

    //foreach loop here
    var comment = document.getElementsByTagName("textarea");
    for($i=0; $i < comment.length; $i++) {
        fieldName = comment.name; // I want to the field name insode validate below
        console.log(fieldName);
        $("#update_comment").validate({
            rules: {
                fieldName: {
                    allowedChars: true
                }
            },
            messages: {
                fieldName: "Allowed special characters: _@./*!\'\"#&+-"
            }
    });

};

考虑以下因素。

var $fieldName;
$.validator.addMethod("allowedChars", function(value) {
  var reg = /^[A-Za-z0-9 _@./*!'"#&+-]*$/;
  return reg.test(value);
});
var opts = {
  rules: {},
  messages: {}
};

//foreach loop here
$("textarea").each(function(i, el) {
  $fieldName = $(el).attr("name");
  console.log($fieldName);
  opts.rules[$filedname] = {
    allowedChars: true
  }
  opts.messages[$fieldName] = "Allowed special characters: _@./*!\'\"#&+-";
});

$("#update_comment").validate(opts);

基于以下文档:https://jqueryvalidation.org/validate/

不确定这是否是正确的库或版本,因为你没有包含它们,但我认为它是正确的。

Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions.

例如,如果您有 3 个文本区域,名称分别为:Text1、Text2、Text3。生成的对象应如下所示。

{
  rules: {
    Text1: {
      allowedChars: true
    },
    Text2: {
      allowedChars: true
    },
    Text3: {
      allowedChars: true
    }
  },
  messages: {
    Text1: "Allowed special characters: _@./*!\'\"#&+-",
    Text2: "Allowed special characters: _@./*!\'\"#&+-",
    Text3: "Allowed special characters: _@./*!\'\"#&+-",
  }
}