0

I was writing code for implementing validation on a input text box. Which should allow the user to enter only numbers. Almost succeeded in implementing this functionality, but faced one difficulty : I'm not able to delete the last character entered.

app.directive('num', function () {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, el, attrs, ctrl) {

        var lastValidValue;
        var NUMBER_REGEXP = /^[0-9]+$/;
        ctrl.$parsers.push(function (value) {
            console.log('inside parsers')
            console.log("Last " + lastValidValue + ", View " + ctrl.$viewValue + ", model " + ctrl.$viewValue);
            if (NUMBER_REGEXP.test(value)) {
                console.log('true')
                lastValidValue = value;
            }
            else {
                ctrl.$viewValue = lastValidValue;
                ctrl.$render();
            }
            console.log("Last " + lastValidValue + ", View " + ctrl.$viewValue + ", model " + ctrl.$viewValue);
            return lastValidValue;
        });
    }
}

})

Please help me to tackle the issue.

1 Answer 1

1

Try changing if (NUMBER_REGEXP.test(value)) to if (NUMBER_REGEXP.test(value) || value == '')

Sign up to request clarification or add additional context in comments.

2 Comments

That worked. Thanks a lot. Could u pls tell me what I did wrong?
So you coded the directive so that it only allows numbers (your regex pattern)...empty or '' doesn't count as a number so you have to consider/allow for that case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.