(function(angular) {
'use strict';
var app = angular.module('form-example1', []);
app.directive('valid.months', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.valid_months = function(modelValue, viewValue) {
// alert(viewValue)
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
const regex = new RegExp('^([1-9]|1[012])$');
return viewValue
.trim()
.split(',')
.every((num) => regex.test(num.trim()));
};
},
};
});
app.directive('unique.months', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.unique_months = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
const months = viewValue
.trim()
.split(',')
.map((m) => m.trim());
return new Set(months).size === months.length;
};
},
};
});
})(window.angular);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-forms-async-validation-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="form-example1">
<form name="form" class="css-form" novalidate>
<div>
<label>
Months:
<input type="text" ng-model="size" name="size" valid.months unique.months />{{size}}</label><br />
<span ng-show="form.size.$error.valid_months">The month(s) list format is invalid!. Allowed digits include: 1,2,3,4,5,6,7,8,9,10,11,12. Correct format: 1, 2, 3, 5</span>
<br />
<span ng-show="form.size.$error.unique_months">The month(s) list specified contains duplicates!. Correct format: 1, 2, 3, 5</span>
</div>
</form>
</body>
</html>