Martin Wickman Martin Wickman - 5 months ago 8
AngularJS Question

How can I simplify form validation?

The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty + invalid and a Great! message if the field is dirty + valid.

But it's a mess having repeat this code for each and every field in the form:

<form name="myForm">
<div class="control-group"
ng-class="{error: myForm.name.$invalid && myForm.name.$dirty}">
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" required/>
<span ng-show="myForm.name.$invalid && myForm.name.$dirty"
class="help-inline">Name is required</span>
<span ng-show="myForm.names.$valid && myForm.names.$dirty">Great!</span>
</div>
</form>


I would like to be able to specify the
ng-show
and
ng-class
attributes in some easier way.

Answer

One way you could do it is to abstract your validation expression to scope methods:

PLUNKER

HTML

<div class="control-group" ng-class="{error: isInvalid('name')}">
  <label>Name:</label>
  <input type="text" name="name" placeholder="Name" ng-model="user.name" required/>
  <span ng-show="isInvalid('name')" class="help-inline">Name is required</span>
  <span ng-show="isValid('name')">Great!</span>
</div>

Controller

function Ctrl($scope) {
  $scope.isInvalid = function(field){
    return $scope.myForm[field].$invalid && $scope.myForm[field].$dirty;
  };

  $scope.isValid = function(field){
    return $scope.myForm[field].$valid && $scope.myForm[field].$dirty;
  };

}
Comments