How to create a js function directive

Asked

Viewed 286 times

2

I have a function to validate date:

   function validateDate(id) {
     var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])    [\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;

     if (!((id.value.match(RegExPattern)) && (id.value!=''))) {
      return false;

       }
      else
     return true;
   }

How would I look to create a directive of this function to use directly in input?

  • Depends, could you provide more details? @War Lock

  • There is no need to create a directive to validate date, use the filter date: https://docs.angularjs.org/api/ng/filter/date

  • And to check if it is a date: https://docs.angularjs.org/api/ng/function/angular.isDate

1 answer

3


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

  • As it would look in fact, the call in my html?

  • You can define an input template and include the element in your HTML, or you can change the line restrict: "E" for restrict: "A" and add as attribute to the element you want to perform the validation.

  • Gobbo A. De Oliv can you edit your answer, with my full function? I will edit the question with the full function, put it as it would be with it.because I’m not getting it, it’s a function q checks whether the date is valid, returns true or false;

  • I did the editing, but I didn’t exactly use your method. Your Regex is strange, and too complex, especially when the browser has native features (Date.parse) to interpret and validate dates. See my issue at the end of the question.

  • Thus validates tbm bisext years?

  • Yes. It is the native format and advised to manipulate dates.

  • 1

    Thank you...worked here

  • @Wineusgobboa.deOliveira taking advantage of the topic, can you post the validation next to the html running? if possible? because I’m starting to study angular, including me who answered to him the function with regular expression on another topic, and I’m needing that too but at an angle, and I couldn’t implement the directive at first.If I can post as I would in practice in jsfidle, or pure code would help me, thanks.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.