Home > other >  jQuery Validation on dynamic form
jQuery Validation on dynamic form

Time:02-08

I'm working on a legacy app that uses jquery validation on a dynamic form. Now I'm trying to pass the name of each textarea input to the validation but doesn't work or maybe I'm doing it wrong. I want to the fieldName variable inside validate(see below).

<form  id="update_comment">
  @foreach($user as $key => user)
   <textarea  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: _@./*!\'\"#& -"
            }
    });

};

CodePudding user response:

Consider the following.

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);

Based on the following Docs: https://jqueryvalidation.org/validate/

Not sure if that is the correct library or version, since you didn't include them, but I think it's right.

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.

For example, if you have 3 Text Areas with Names: Text1, Text2, Text3. The resulting Object should look like this.

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

No way to test as you have not presented a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example

  •  Tags:  
  • Related