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 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: _@./*!\'\"#&+-"
}
});
};
$("textarea")?console.log(comment.name)What do you get?commentis eventually a collection of multiple elements! Not ONE. If you want to target the iterating element usecomment[i], notcomment$("#update_comment").validate({inside a for loop? Isn't enough to set the validation rules once? ;)