Tuesday, 26 April 2016

Disable submit button until all mandatory fields are filled - Angular

Here I am going to explain how we can disable a submit button using a simple reusable directive until all the mandatory fields are filled.Let us start with a simple form first


<div ng-app="sampleapp">
    <div ng-controller="samplecontoller" >
     <form name="form" disable-btn ng-submit="submitForm()">
          <input type="text" ng-model="model.name" required></input>
        <input type="number" ng-model="model.number" required></input>
        <button class="btn btn-primary" type="submit">Submit</button>

In the above html "disable-btn" is the directive which we are going to create. I have marked both fields are mandatory using required attribute. Let us start with our directive.

Angular directive for disabling submit button

function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
    } else {
     submitBtn.attr('disabled', 'disabled');

We are done with our directive, now you can see that submit button will be disabled until all the mandatory fields are filled. Check the below fiddle and see how it is working.

Using the same directive you can handle pattern validation as well. Also you can set max length/min length. For example see the below sample form.

<input type="number"placeholder="Last Name"  ng-model="model.age" required></input>

<input type="text" ng-model="model.city" ng-minlength="2" ng-maxlength="20" required>

<input type="text" ng-model="model.phoneNumber" pattern="^(?=.*?[1-9])[0-9()-]+$" 
maxlength="25" placeholder="Phone Number" />  

Related Posts

1. Angular js client side pagination like google.

2. Angular Loader using font awesome icons

3. Angular js add class to active element

No comments :

Post a Comment