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.

1

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

My form is more an application so I dont have all inputs in the same container.
That looks nice. I will try it tomorrow. Thank you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.