By name of its function, it is a validation function.
You must configure the validators in the ngModelController of Directive. The ngModelController is the 4th parameter of the property link of a Directive.
For example:
angular.module("Modulo").directive("diretriz", function () {
"use strict";
return {
restrict: "E",
require: "ngModel",
link: function ($s, $e, $a, $c) {
$c.$validators.data = function (mv, vv) {
// mv é o valor na sua variável.
// vv é o valor na view.
if ( vv === "" ) {
return true;
}
vv = vv.split("/");
if ( vv.length !== 3 ) {
return false;
}
vv.reverse();
vv = vv.join("-");
return !isNaN(Date.parse(vv)));
};
}
};
});
Note that at the property link, the function associated with it accepts 4 parameters:
$s is the scope;
$e is the element encased in jQuery or jQuerylite;
$a are the attributes of the element;
$c is the ngModelController.
The attribute $validators of ngModelController has the "validators" of its directive. They return true or false. All the validators are executed during the validation process, and the element(s) associated with the guideline are considered valid if and only if all validators return true.
An interesting feature of validators in Angular, is that when an element has the attribute required, is checked only if its value is different from false (including values that can be coerced into false, as the number 0).
As a consequence, its Validator can return true when the field is empty (even if this is an invalid value), and you can force the field to be filled using the attribute required. This way, you can differentiate when the element is invalid by containing a value that does not comply with its rules, or when the element is empty, and even decorate the element through CSS when one case or another without any additional code (note the classes added by Angular to the element when it is invalid, empty or valid).
The ngModelController has several other interesting fields besides the $validator, like the $parsers and the $formatters. It is very worth taking a look at them in the documentation.
Editing
I didn’t use your Regex because it is too complex, especially when the browser has native features to interpret dates. So the validator I wrote converts the date into the format dd/mm/yyyy for the format yyyy-mm-dd (ISO 8601), natively accepted by the browser in the method Date.parse.
Although I didn’t use Regex, I tried to preserve the same semantics as your method. So the two should be equivalent (with the advantage that my Czech if the year is leap).
Depends, could you provide more details? @War Lock
– Roger Oliveira
There is no need to create a directive to validate date, use the filter date: https://docs.angularjs.org/api/ng/filter/date
– Ivan Ferrer
And to check if it is a date: https://docs.angularjs.org/api/ng/function/angular.isDate
– Ivan Ferrer