This question already has an answer here:
- adding jquery validation dynamically 3 answers
I am using jQuery validation library for validating my forms created using Angular.JS. I am able to add validations on all static/known input fields in the form.
Along with fix inputs I am going to have some dynamic questions in the form. These questions are going to get rendered using ng-repeat
directive.
I am able to validate input only if id
and name
of the input control are known. In case of dynamic control we can not predict the same.
HTML Code:
<body>
<div ng-controller="PersonController">
<div ng-repeat="social in formData.socials">
<ng-form name="urlForm">
<input type="url" name="socialUrl" ng-model="social.url">
<span class="alert error" ng-show="urlForm.socialUrl.$error.url">URL error</span>
</ng-form>
</div>
<hr>
<form id="contact-form">
<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" name="email" id="email" placeholder="Your email address">
</div>
</div>
<br/>
<div ng-repeat="question in Questions">
<label class="control-label" for="email">{{question.Title}}</label>
<div class="controls">
<input name="question">
</div>
<br/>
</div>
</form>
</div>
</body>
I have checked the approach of validating dynamic input control using ng-form
element. But I want to validate the form using jQuery validation only as I am going to have jQuery bootstrap popovers which works along with jQuery Validation only.
Javascript:
angular.module('directive', []).controller('PersonController', function personController($scope) {
$scope.loading = false;
$scope.formData = {
socials: [{
url: 'http://www.valid.com'},
{
url: 'invalid url'}]
};
$scope.Questions = [
{ "Title": "Whats your name?", "Type": "Text" },
{ "Title": "Whats your birthdate?", "Type": "Date" }
];
$(document).ready(function () {
$('#contact-form').validate({
rules: {
email: {
required: true,
email: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
});
Please refer this: http://plnkr.co/edit/3jiYucTKOlW4G0TISFNj?p=preview
How can I add jQuery validation rule for dynamic element? Please help me out. Thanks in advance.