0

I am trying to validate input for date (dd/mm/yyy) and then if it is not date don't allow to enter - such as strings or anything

Below is my code but not working - means allowing users to enter anything

angular.module('app')
.directive('onlyDates', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attr, ctrl) {
            function inputValue(val) {
                if (val) {
                    var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;
                    var res = reg.test(val);
                    if (!res) {
                        ctrl.$setViewValue(val);
                        ctrl.$render();
                        return NaN;
                    }
                    return val;
                }
                return undefined;
            }
            ctrl.$parsers.push(inputValue);
        }
    };
});
Pangaluri S
  • 83
  • 1
  • 2
  • 8

1 Answers1

0

you could try using ng-change and some function that can check "as you type" that what you are entering matches your pattern, and if not, delete the last char entered.

<input type="text" ng-model="txtValue" ng-change="TextBoxChangedCheck()">


$scope.TextBoxChangedCheck = function () {
            //// enter your text validation here
        };
JulioCT
  • 1,057
  • 8
  • 7
  • It's not user friendly to modify the value as users are inputting it. Allow them to finish, then check. E.g. if they mistype a character, then press delete to remove it, the function may have already deleted the mistyped character so they delete an extra one, then continue typing from where they thought they were in the pattern, which likely creates another error, and so on. – RobG Mar 03 '16 at 21:00
  • yes, maybe it is not, but anyway the user experience would be like when you have a numeric only field – JulioCT Mar 03 '16 at 21:09