-
Key pressed validation in angularJS
about 9 years ago
-
about 9 years ago
Hi Bhagwan
Create html page and put below code. In which text field accept only basis of valid pattern.
<body ng-app="CodePenApp"> ALPHA ONLY <input type="text" allow-pattern="[a-z]" /> <br> NUMBER ONLY <input type="text" allow-pattern="\d" /> <br> ALPHANUMERIC ONLY <input type="text" allow-pattern="(\d|[a-z])" /> <br> WHITESPACE CHARACTERS ONLY <input type="text" allow-pattern="\W" /> <br> ABCDEFG ONLY <input type="text" allow-pattern="[ABCDEFG]" /> </body>
Create controller for the above html code.
var app = angular.module("CodePenApp",[]); app.directive('allowPattern', [allowPatternDirective]); function allowPatternDirective() { return { restrict: "A", compile: function(tElement, tAttrs) { return function(scope, element, attrs) { // I handle key events element.bind("keypress", function(event) { var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event. var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode. // If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field. if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) { event.preventDefault(); return false; } }); }; } }; }
1 Answer(s)