1

I am using angular form validation like this:

<input type="text" class="form-control" id="Name" ng-model="name" ng-required="true" name="name" ng-class="{true: 'error'}[validationForm.name.$invalid]" ng-model-options="{ updateOn: 'blur' }">
<p ng-show="validationForm.name.$error.required && validationForm.name.$dirty">
    Name is required.
</p>

A lot of the HTML Code is used only for the validation - 4 attributes in the input element. Is it possible to set only 1 attribute for "custom validation" and implement the other stuff in my JavaScript code? I think that would result in cleaner code and save a lot of time if I have ~20 inputs.

stefanhorne
  • 1,619
  • 3
  • 16
  • 23
Chris
  • 159
  • 1
  • 13
  • Check out this question : http://stackoverflow.com/questions/12581439/how-to-add-custom-validation-to-an-angularjs-form – b-m-f May 03 '16 at 09:39

1 Answers1

2

Why you don't use ng-repeat?

<div ng-repeat"item in items">
    <input type="text" class="form-control" id="{{item.id}}" ng-model="item.model" ng-required="item.required" name="{{item.name}}" ng-class="{true: 'error'}[validationForm.{{item.name}}.$invalid]" ng-model-options="{ updateOn: 'blur' }">
    <p ng-show="validationForm.{{item.name}}.$error.required && validationForm.{{item.name}}.$dirty">
       {{item.errorMessage}}
    </p>
</div>

and then in your controller

$scope.items = [{
    id: "id1",
    name: "name1",
    model: "your starting value",
    errorMessage: "Name is required.",
    required: true,
  },
  {
    ...
  }
]

Edit:

You can use a custom directive to do the same at different locations

<my-input  data="items[0]" myform="validationForm"></my-input>

and then your directive

.directive('myInput', function() {
  return {
    restrict: 'E',
    scope: {
        data: '=',
        myform: '='
    },
    templateUrl: 'myInput.html'
  };
});

Content of myInput.html

   <input type="text" class="form-control" id="{{data.id}}" ng-model="data.model" ng-required="data.required" name="{{data.name}}" ng-class="{true: 'error'}[myform.{{data.name}}.$invalid]" ng-model-options="{ updateOn: 'blur' }">
    <p ng-show="myform.{{data.name}}.$error.required && myform.{{data.name}}.$dirty">
       {{data.errorMessage}}
    </p>
Simon Schüpbach
  • 2,625
  • 2
  • 13
  • 26