Introduction
In this article I'll tell you about How to Retain Focus on Invalid Field using AngularJS Custom Directive.
Directives can be created for validation purpose but here I am not explaining those as some directives are already available for validation purpose, but you can download the source code and can get the directive from controller.js.
Let's see how to retain focus on invalid field through a simple application.
Step 1: Firstly, I created an HTML page where some controls are created and angular validation is applied.
- <!DOCTYPE html>
- <html>
- <head>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
- <script src="Controller.js"></script>
- </head>
- <body>
- <form ng-app="TestFormMod" name="ApplicantCustomerProfile" ng-controller="TestFormCtrl" novalidate angular-validator >
- <div class="gloabl-form-content">
-
- <div class="row">
- <div class="col yellow-divider">
- <div class="col-first">
- <label><span class="asterisk">*</span>Name of father/Guardian</label>
- </div>
- <div class="col-second">
- <input name="guardian_or_father_name"
- type="text"
- name="fatherName"
- ng-model="customer_profile.guardian_or_father_name"
- validate-on="blur"
- ng-pattern="/^[ a-zA-Z]*$/"
- required
- required-message="'Please enter father name.'"
- invalid-message="'Only alphabets are allowed'"
- maxlength="100" />
- </div>
- <div class="col-third">
- <label>Name of Spouse</label>
- </div>
- <div class="col-four">
- <input name="spouse_name" type="text" ng-model="customer_profile.spouse_name"
- validate-on="blur"
- ng-pattern="/^[ a-zA-Z]*$/"
- invalid-message="'Only alphabets are allowed'"
- maxlength="100" />
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col yellow-divider">
- <div class="col-third">
- <label><span class="asterisk">*</span>Phone Number</label>
- </div>
- <div class="col-four">
- <input type="text"
- name="annual_turnover"
- ng-model="customer_profile.annual_turnover"
- validate-on="blur"
- ng-pattern="/^[ 0-9.]*$/"
- required
- required-message="'Please enter mobile number'"
- invalid-message="'Only numbers are allowed.'" />
- </div>
- </div>
- </div>
-
- </div>
- </form>
- </body>
- </html>
- <style>
- input.apply-visited.ng-invalid:not(.apply-focus)
- {
- background-color: #ffeeee;
- }
- </style>
Here you can see that I had applied different kind of validation on three controls: required, number only, alphbets only.
You can see in the form tag that I had applied a directive named "angular-validator", this is the same directive which is used to apply the validations and you can get that from source code.
Step 2:
Now let's create a JavaScript file where controller will be created.
I created a controller named "TestFormCtrl", here you can write any code according to your requirements.
- angular.module('TestFormMod', [])
-
- .controller('TestFormCtrl', function ($scope, $location, $rootScope) {
-
- })
Step 3
After this I had created two directives which will help to retain focus on input fields.
- .directive("parentDirective", function () {
- return {
- restrict: 'A',
- require: ['form'],
- controller: function () {
-
- },
- link: function (scope, ele, attrs, controllers) {
- var formCtrl = controllers[0];
- }
- };
- })
-
- .directive('input', function () {
- return {
- restrict: 'E',
- priority: -1000,
- require: ['^?parentDirective', '^?angularValidator'],
- link: function (scope, elm, attr, ctrl) {
- if (!ctrl) {
- return;
- }
-
- elm.on('focus', function () {
- elm.addClass('apply-focus');
-
- scope.$apply(function () {
- ctrl.hasFocus = true;
- });
- });
-
- elm.on('blur', function () {
- elm.removeClass('apply-focus');
- elm.addClass('apply-visited');
-
- scope.$apply(function () {
- ctrl.hasFocus = true;
- ctrl.hasVisited = true;
-
- });
- });
-
- }
- };
- });
First one is like a parent directive and second one will work only when we are having parent directive and validator directive. Second directive will help to retain focus on elements.
Now you just need to call this directive in the form tag of your page.
- <form ng-app="TestFormMod" name="ApplicantCustomerProfile" ng-controller="TestFormCtrl" novalidate angular-validator parent-directive>
Here I am only providing code for those conditions where user will not be able to move from one control to second unless he / she fulfills the validations, but if user click on button which is on master page and have some other controller then this code is not enough to stop the user from navigation. In that case you need to do modifications in your code and need to check whether page is valid or not, if not then you just need to stop the navigation as this code will be still working.
Output
Let's run the application and see the output.
On running the application three textbox will appear.
Now just click on required textbox and try to leave the textbox without filling the value.
Even if you enter the wrong value then also it will not allow you to leave the textbox.