Almost every website uses forms to perform different tasks, such as registering users or getting their contact information. It is important to ensure that the user filling out the form at least enters valid information into the input fields.
A detailed error message also needs to be shown to the user so they can fill out the form correctly. This process can get very complicated when you have to deal with a large number of form elements, each of which requires its own custom error message. To ease the pain, Angular 1.3 adds a new module called ngMessages to help developers easily validate forms.
ngMessages module enables you to display custom error messages to users without writing duplicate code. In this tutorial, you will learn how to use this module to validate your forms. You'll also learn how to load error messages from outside and only display messages when actually needed.
Let us first validate a single input field with or without the help of ngMessages to understand the usefulness of this module. Without ngMessages, the markup of the input element would look like the following code:
<form name="formValidation"> <label>Username</label> <input type="text" name="username" ng-model="inputname" ng-minlength="6" ng-maxlength="12" required> <p ng-show="formValidation.username.$error.minlength">Username should have at least 6 characters.</p> <p ng-show="formValidation.username.$error.maxlength">Username should have at most 12 characters.</p> <p ng-show="formValidation.username.$error.required">Providing a username is mandatory.</p> </form>
You also need the following JavaScript code:
angular.module('app', []);
All other form elements require similar validation. This will make the markup very repetitive, increasing the chance of errors. If you decide to use ngMessages to validate the same form input, the markup will look like the following code:
<form name="formValidation"> <label>Username</label> <input type="text" name="username" ng-model="inputname" ng-minlength="6" ng-maxlength="12" required> <div ng-messages="formValidation.username.$error"> <p ng-message="minlength">Username should have at least 6 characters.</p> <p ng-message="maxlength">Username should have at most 12 characters.</p> <p ng-message="required">Providing a username is mandatory.</p> </div> </form>
The JavaScript code will now become:
angular.module('app', ['ngMessages']);
Here we use the ng-messages
directive to group error messages together. The values passed to the ng-messages
directive follow the pattern formName.inputName.$error
. In our example, this evaluates to formValidation.username.$error
.
Similarly, you can also get the values of the ng-messages
directive for all other fields. ngMessages relies on the $error
object exposed by the ngModel directive to determine whether error messages should be shown or hidden on the web page. It loops through the $error
objects, looking for keys that match the value of any ng-message
directive.
Here is a working example showing the above validation code in action:
In this section we will validate a form containing username, password and email fields. The form's markup will resemble the following code:
<form name="formValidation"> <label>Username</label> <input type="text" name="username" ng-model="inputName" ng-minlength="6" ng-maxlength="12" ng-pattern="/^\w+$/" required> <div ng-messages="formValidation.username.$error"> <p ng-message="minlength">Username should have at least 6 characters.</p> <p ng-message="maxlength">Username should have at most 12 characters.</p> <p ng-message="required">Providing a username is mandatory.</p> <p ng-message="pattern">Username can only be alphanumeric with an optional underscore.</p> </div> <label>Password</label> <input type="text" name="userPassword" ng-model="inputPassword" ng-minlength="6" ng-maxlength="12" required> <div ng-messages="formValidation.userPassword.$error"> <p ng-message="minlength">Password should have at least 6 characters.</p> <p ng-message="maxlength">Password should have at most 12 characters.</p> <p ng-message="required">Providing a password is mandatory.</p> </div> <label>Email</label> <input type="email" name="userEmail" ng-model="inputEmail" required> <div ng-messages="formValidation.userEmail.$error"> <p ng-message="email">Please enter a valid email address.</p> <p ng-message="required">Providing an email is mandatory.</p> </div> </form>
As you can see, the markup required to validate different form elements is very similar. An important change in this example is the addition of the ng-pattern
directive. The pattern we use here ensures that the username entered contains only alphanumeric characters and underscores. \w
in /^\w $/
represents word characters such as A-Z, a-z, 0-9, and _.
You should try entering a different username in the Username field. After a while, you'll notice that if you type a character before the first 6 characters or after the first 12 characters, the form doesn't complain that the character is not alphanumeric. This behavior is not very user friendly.
For example, let's say some of your users have usernames that start with an exclamation point. They have to wait until they enter six more characters before they get an error about using only alphanumeric characters. It would be very frustrating if they started typing in their username again from scratch.
By default, ngMessages only displays one error to the user at a time. This is why the message about invalid characters cannot be displayed until the user enters more than six characters. Additionally, ngMessages uses the order in which you enter error messages as a hint to prioritize them.
If you provide a minimum character message before an alphanumeric error occurs, ngMessages will wait until the minimum character error is resolved before displaying the alphanumeric error.
This is the same form, but the error messages are displayed in a different order.
You can also use ng-messages-multiple
to display all applicable error messages to the user at once. However, once users start typing in the input field, they see multiple error messages, which can be overwhelming.
我们的标记中仍然有很多重复。如果您想为不同的输入字段显示相同的错误消息,则为每个输入字段重复它是没有意义的。 ngMessages 模块可以帮助您仅编写一次通用错误消息,并在需要时将它们包含在您的表单中。以下是创建向用户显示通用错误消息的表单的标记。
<script type="text/ng-template" id="generic-messages"> <p ng-message="required">This field is required.</p> <p ng-message="minlength">This field is too short.</p> <p ng-message="maxlength">This field is too long.</p> </script> <form name="formValidation"> <label>Username</label> <input type="text" name="username" ng-model="inputName" ng-minlength="6" ng-maxlength="12" ng-pattern="/^\w+$/" required> <div ng-messages="formValidation.username.$error"> <p ng-message="pattern">Username can only be alphanumeric with an optional underscore.</p> <p ng-message="maxlength">Username cannot be longer than 12 characters.</p> <div ng-messages-include="generic-messages"></div> </div> <label>Password</label> <input type="text" name="userPassword" ng-model="inputPassword" ng-minlength="6" ng-maxlength="12" required> <div ng-messages="formValidation.userPassword.$error"> <div ng-messages-include="generic-messages"></div> </div> <label>Email</label> <input type="email" name="userEmail" ng-model="inputEmail" required> <div ng-messages="formValidation.userEmail.$error"> <p ng-message="required">This field is required.</p> <p ng-message="email">Please enter a valid email address.</p> </div> </form>
就像前面的情况一样,消息的优先级由其在模板中的位置决定。您还可以通过在各个字段中包含自定义错误消息来覆盖模板中提供的通用消息。还可以使用以下代码从单独的文件加载错误消息:
<div ng-messages="formValidation.userPassword.$error"> <div ng-messages-include="path/to/generic-messages.html"></div> </div>
您可以通过仅在用户在填写表单时实际出错时显示错误消息,使表单更加用户友好。例如,您可以选择仅在用户实际跳过输入元素时显示必填字段错误。
这可以通过使用 ng-show
或 ng-if
指令以及 $touched
和 $dirty
。对于 $touched
,一旦输入失去焦点,就会显示错误消息。对于 $dirty
,一旦输入无效就会显示错误消息。
<div ng-messages="form.username.$error" ng-if="form.username.$touched"> <div ng-messages="form.username.$error" ng-if="form.username.$dirty"> <div ng-messages="form.username.$error" ng-show="form.username.$touched"> <div ng-messages="form.username.$error" ng-show="form.username.$dirty">
这是显示 $touched
和 $dirty
之间区别的演示。
在本教程中,您了解了使用 ngMessages 验证不同类型表单元素的输入是多么容易。您还学习了如何多次重复使用相同的错误消息以避免重复,以及如何确定不同错误消息的优先级。
您还可以同时使用 ngMessages 和 ngAnimate 来使用自定义动画来显示或隐藏错误消息。有关使用 ngAnimate 模块的教程也将很快在 Envato Tuts+ 上发布。
如果您想与其他读者分享任何提示,或者有任何问题想问,请在评论中告诉我。
The above is the detailed content of AngularJS form validation using ngMessages. For more information, please follow other related articles on the PHP Chinese website!