Arash bahreini Arash bahreini - 1 year ago 96
AngularJS Question

angularJS required is not working in directive

Hope you all doing well.

I have an input="text" which has required (validation for not empt) attribute of angularJS.

The below js 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) {
return transformedInput;
return undefined;

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

Answer Source

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

You need to change the

return undefined;


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download