Tuesday, December 13, 2016

Angularjs Focus Specific Error Input On Form Submit

<!doctype html>
<html>
<head>
    <title>Angularjs Focus Specific Error Input On Form Submit</title>
    <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>

<div data-ng-app="myApp" data-ng-controller="MyController">
    <form name="myForm" method="get" validate-form novalidate>
        <div class="container">
            Name: <input type="text" name="name" ng-model="name" ng-required="true" ng-maxlength="10" ng-minlength="5" my-validation/>
        </div>
        <div class="container">
            Email: <input type="email" name="email" ng-model="email" ng-required="true" my-validation/>
        </div>
        <div class="container">
            Type:
            <input type="radio" name="type" ng-model="type" value="A" ng-required="true" my-validation/> A
            <input type="radio" name="type" ng-model="type" value="B" ng-required="true" my-validation/> B
            <input type="radio" name="type" ng-model="type" value="C" ng-required="true" my-validation/> C
        </div>
        <div><input type="submit" value="Submit"/></div>
    </form>
</div>

<script type="text/javascript">
    var app = angular.module("myApp", []);

    app.controller("MyController", function($scope) {
        $scope.name = "";
        $scope.email = "";
    });

    app.directive('validateForm', function () {
        return {
            restrict: 'A',
            link: function ($scope, form) {
                form.on('submit', function () {
                    $(form).find(".container").css("border", "");
                    if($scope.myForm.$invalid) {
                        var error = $scope.myForm.$error;
                         for (var key in $scope.myForm.$error) {
                             for (var index = 0; index < $scope.myForm.$error[key].length; index++) {
                                 var err = $scope.myForm.$error[key][index];
                                 console.log("Field=" + err.$name + ', Error=' + key);
                             }
                         }


                        var firstInvalid = $(form[0].querySelector('.ng-invalid'));

                        if (firstInvalid.length > 0) {
                            firstInvalid.closest(".container").addClass("error_element").css("border", "2px solid red");
                            firstInvalid.focus();
                            return;
                        }
                    }
                    alert("Form Validated");
                });
            }
        };
    });

    app.directive("myValidation", function() {
        return {
            restrict: "A",
            require: "ngModel",
            link: function(scope, elem, attrs, ctrl) {
                console.log(attrs)
            }
        }
    })
</script>

</body>
</html>


No comments:

Post a Comment