简体   繁体   中英

angular form validation focus

Trying to do a form validation, when input is empty upon submission it should focus on that empty field. I'm looping through the element.class to do .focus() but I don't know how to find which one is empty and to focus on that field.

var refocusInput = function() {
            $timeout(function(){
                var inputHasError = document.getElementsByClassName("form-control");
                for (var i = 0; i < inputHasError.length; i++) {
                    var element = inputHasError[i];
                    if(element){
                        console.log(inputHasError);
                        inputHasError[i].focus();
                        console.log('focus')
                    }
                }
        })
    }
vm.publishForm = function (){
    refocusInput();
}

you are using angular therefore you can always use the ng-form attribute and the $valid property

the example is from angular documentation link

 angular.module('formExample', []) .controller('FormController', ['$scope', function($scope) { $scope.userType = 'guest'; $scope.submit = function(e) { $scope.isValid = $scope.myForm.$valid } } ]); 
 .my-form { transition: all linear 0.5s; background: transparent; } .my-form.not-valid{ background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="formExample"> <form name="myForm" ng-controller="FormController" ng-class="{'not-valid' : !isValid}" class="my-form"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span> <input type='button' ng-click='submit($event)' value='submit' /> <br> <code>userType = {{userType}}</code> <br> <code>myForm.input.$valid = {{myForm.input.$valid}}</code> <br> <code>myForm.input.$error = {{myForm.input.$error}}</code> <br> <code>myForm.$valid = {{myForm.$valid}}</code> <br> <code>myForm.$error.required = {{!!myForm.$error.required}}</code> <br> </form> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM