Tag Archives: Alphabets

Only Alphabets in AngularJS

The Directive for only alphabets.

The input type text in a HTML5 app allows only text during form submission event, if we try to enter any other character it considers the form invalid and try to show a default respective browser style invalid message, of course we can change the style of message display using a directive.

The below directive completely transforms the input type text to accept only text other characters are restricted.

onlyAlphabets.directive('onlyAlphabets', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            if (!ngModel) {
                return;
            }
            ngModel.$parsers.unshift(function (inputValue) {
                var alphabets = inputValue.split('').filter(function (s) {
                    return (isALetter(s));
                }).join('');
                ngModel.$viewValue = alphabets;
                ngModel.$render();
                return alphabets;
            });
        }
    };

    function isALetter(charVal)
    {
        if( charVal.toUpperCase() != charVal.toLowerCase() ) {
            return true;
        }
        else {
            return false;
        }
    }
});

The above directive ngModel is required through which we are controlling the rendering of characters which is required to display in input text field, the function isALetter logic detects the char entered in input field is alphabets or not.

The ngModel variable contains the function $viewValue which sets the new value to the input text field and $render renders view to display.