Sunday, 12 April 2015

Disable the Form submit button up to all required fields are filled in form using Angular js

In this post we are going to see how to disable the submit button in form up to all required fields are filled in form using angular js.

Already Angular Js have one option to do this by using the formname.$Invalid check with ng-disabled, But this option is not working as Expected for me, may be some bug in angular js. so I implemented my own implementation of directive check which will do the same functionality for us.



First the functionality that required for us

1. Form should have user name and password
2. Form submit button should be disbaled , up to all required fields are filled with valid value.
3. Enable the submit button when all fields are filled with correct value.


Angular directive:
*********************

<form method="post" action="/Validation/Login" validate-invalid>
   <button ng-disabled="!form.enableSubmit" type="submit" >Sign in</button>

</form>

Our sample HTML5 code will look like above code, Form tag have a button inside that a custom directive validate-invalid is placed in form tag, this is our directive which will let you that submit button is enabled or disabled by placing the property of  ng-disabled="!form.enableSubmit"  in button tag

So let we see our custom directive code .

var mainApp = angular.module('mainApp', []);


mainApp.directive('validateInvalid', function () {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {

            if (scope.form == undefined)
                scope.form = {};

            element.addClass('ng-invalid');

            scope.form.enableSubmit = false;

            scope.$watch(function () {
                return element.attr('class');
            }, function (val) {
                var valid = true;
                var classes = val.split(" ");

                angular.forEach(classes, function (classname) {
                    if (classname == "ng-invalid") {
                        valid = false;
                    }                   
                });

                if (valid)
                    scope.form.enableSubmit = true;
                else
                    scope.form.enableSubmit = false;

            });
        }
    }

});

At the first time application launch, Submit button is in disabled state, then further user changes in the form fields it will enable the Submit button, and makes the user to submit there credentials to the server to Login.

At Load:



At some input:



After all Required Fields filled with valid values.




This Post makes you to understand how to make a Login form with automatic submit button disabled and enabled based on attributes.


1 comment:

  1. it there are autofill data the buttons are still shows as disabled.. How to over come that?

    ReplyDelete