0

This is a follow on question for this question:

Server-side validation form Angular.js

So using that answer you could write some HTML in a template that would display a specific error for each error you give $setValidity. For example here is one:

<input ng-model="user.lastName" required="true" id="lastNameField" name="lastName" type="text" class="span3" placeholder="Last Name"/>
<span class="inlineError" ng-show="myProfile.lastName.$error.required">Required</span>

However, if I wanted to add one for last names must be 4 or more characters long I'd have:

<input ng-model="user.lastName" required="true" id="lastNameField" name="lastName" type="text" class="span3" placeholder="Last Name"/>
<span class="inlineError" ng-show="myProfile.lastName.$error.minRequired">Last name must be at least 4 characters long</span>

My question is how could I write a generic handler for all errors on a field. Something like:

<input ng-model="user.lastName" required="true" id="lastNameField" name="lastName" type="text" class="span3" placeholder="Last Name"/>
<span class="inlineError" ng-show="myProfile.lastName.$error.required">{{myProfile.lastName.$error.required}}</span>

Is that possible?

1 Answer 1

4

Do you mean that you just want to indicate the validity of the form element? Then, you can do:

<span ng-show="myProfile.lastName.$invalid">Input field is invalid.</span>

If you need to be more specific, you can use ng-repeat to iterate through myProfile.lastName.$error object and display all the errors. In this case, you'll have to have some error-name to error-message translation for readability.

Sign up to request clarification or add additional context in comments.

1 Comment

That's kinda helpful because I wasn't aware of $invalid, but I really mean the later part where I iterate over all error messages and display them.

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.