Martin Wickman Martin Wickman - 1 year ago 54
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:$invalid &&$dirty}">
<input type="text" name="name" ng-model="" required/>
<span ng-show="$invalid &&$dirty"
class="help-inline">Name is required</span>
<span ng-show="myForm.names.$valid && myForm.names.$dirty">Great!</span>

I would like to be able to specify the
attributes in some easier way.

Answer Source

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



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


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;