Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular blur validation preventing submission of separate form

I have an Angular page with a form for adding people, and a button (outside this form) to submit the list of people.

When the user focuses on a text input in the form, and then clicks to submit the list, the validation error from the text input appears but the submit event never occurs.

An example of this issue here: http://plnkr.co/edit/6Z0UUs

<div ng-controller="MyCtrl as vm">
  <form name="form1" novalidate="">
    <input type="text" name="field1" ng-model="vm.name" required>
    <div ng-messages="form1.field1.$error" ng-if="form1.field1.$touched">
      <label ng-message="required">Name is required</label>
    </div>
    <!-- 
    This form adds a person to a list. I've not included this code to keep the example simple 
    <input type="submit" value="Add person"> 
    -->
  </form>
  <button ng-click="vm.submit()">Submit list</button>
</div>

-

angular.module('myApp',[])
.controller('MyCtrl', function() {
    var vm = this;

    vm.name = '';

    vm.submit = function () {
        alert('submitted');    
    };
});

To replicate:

  1. Click on the text input but leave blank
  2. Click submit

Current behavior: "Name is required" appears thanks to the validation. Clicking 'Submit' again displays the 'submitted' alert.

Expected behavior: "Name is required" appears thanks to the validation and the 'submitted' alert appears.

Desired behavior: The 'submitted' alert appears and I add some code to vm.submit() to hide the 'Name is required' validation message as it's not important when the list is submitted.

I've observed that removing the ng-messages block fixes the issue, but I do need to show a validation message. Using a more basic directive (ng-show) to show the validation message instead does not help.

Any insights into what I'm doing wrong, or workarounds to achieve my desired behavior, would be great!

like image 666
Paddy Mann Avatar asked Aug 19 '15 13:08

Paddy Mann


1 Answers

[Modified Answer] : Here is a working plunker : http://plnkr.co/edit/JCyRi8xp4L3FtafABblS?p=preview

vm.preventDefaultIfSubmitted = function($event){
if($event.relatedTarget.id == "submit"){
    $event.stopImmediatePropagation();
  }
};

The idea is to get the $event when the blur occurs and then to look at the id of the relatedTarget (which is your button in this case) and if it is then you cancel the $event, otherwise you keep it.

That way if you click anywhere your validation message appears and if you click on submit it doesnt

like image 106
ThibaudL Avatar answered Sep 27 '22 20:09

ThibaudL