ng-disabled in Angular validation not working as expected

Issue

http://plnkr.co/edit/9Yq6aZHtKCuZMtPbjBIN?p=preview

I’ve tried and tried to get this to work but I’ve had no luck. I’m trying to disable the submit button using angularJS and the built in validation function. What I find is that when you first load the form, the submit button is active–not disabled!

I’ve tested and tried and I’ve found that my validation code accepts an empty string / null string in the Team Name, despite me requiring the input.

Does anyone know how to format this correctly? The ONLY way I’ve gotten it to work is to fudge the data with replacing an empty string with a single space…in production this is unacceptable…

Here is the index.html:

<body ng-controller="EnterController as enter">
  <div class="panel panel-primary">
    <div class="panel-body">
      <form name="enterFormNew" ng-submit="enter.TeamNameNext()" autocomplete="off" novalidate>
        <div class="row">
          <div class="col-xs-8 col-md-6">
            <div class="form-group">
              <label for="teamname">Team Name</label>
              <input name="TeamName" ng-required ng-minlength="2" ng-maxlength="40" ng-model="enter.Team.Name" type="text" id="teamname" class="form-control" />
              <p ng-show="enterFormNew.TeamName.$touched && enterFormNew.TeamName.$invalid">This is not a valid team name.</p>
            </div>
            <div class="form-group">
              <label for="division">Division</label>
              <select name="selectDivision" ng-required ng-model="enter.Team.Division" id="division" class="form-control" ng-options="division.Name for division in enter.Divisions track by division.Id ">
                <option value="">Select...</option>
              </select>
              <p ng-show="enterFormNew.selectDivision.$touched && enterFormNew.selectDivision.$invalid">A valid Division needs to be selected.</p>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-2">
            <button type="submit" class="btn btn-primary" ng-disabled="enterFormNew.$invalid">Next</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</body>

And here is the app.js:

angular.module('Enter', [])
.controller("EnterController", [
  function() {
    this.RegistrationPhase = 0; 

    this.Divisions = [{ Id: 1,Name: "Normal"}, {Id: 2,Name: "Not Normal"}];

    this.Team = { Name: "", ResumeKey: null, Division: { Id: -1 }, Players: []};

    this.TeamNameNext = function() {
      //Code removed

      alert("Made it to the submit function!")

    };

  }
]);

Solution

the attribute ng-required requires a value. Don’t get confused with HTML5 attribute required that doesn’t require a value.

ng-required="true"

Answered By – ThiagoPXP

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.