0

I have an input="text" which is required.

The below code is a directive for text which force user to type only numbers.

By its default required warning is ON. Now the problem is if you type any keyword except numbers in the textbox, it will not type the character ( which is fine ) but the required error will disappear!!!!!! the result is a textbox with empty value and not required error message !!!

angular.module('league').directive('numbersOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.replace(/[^0-9]/g, '');

                    if (transformedInput !== text) {
                        ngModelCtrl.$setViewValue(transformedInput);
                        ngModelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }            
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});



 
<input type="text" class="CreateTxt" ng-model="league.name" name="leagueName" required />
<span ng-show="myForm.leagueName.$error.required" style="color:red">Its required...</span>

1 Answer 1

1

Couldn't you achieve the same behavior with using type="number"?

You need to change the

return undefined;

to

return null;

Otherwise angular will result in parse error, which is not required error. So you did almost everything good except your choice for the fallback value.

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

1 Comment

i dont want to use of type=number because it allow users to type 'e' and some other problems are there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.