Table of Contents
A basic example
Verification form
重用错误消息
仅在需要时显示错误
结论
Home Web Front-end JS Tutorial AngularJS form validation using ngMessages

AngularJS form validation using ngMessages

Sep 01, 2023 pm 10:05 PM
angularjs form validation ngmessages

AngularJS form validation using ngMessages

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.

A basic example

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>
Copy after login

You also need the following JavaScript code:

angular.module('app', []);
Copy after login

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>
Copy after login

The JavaScript code will now become:

angular.module('app', ['ngMessages']);
Copy after login

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:

Verification form

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>
Copy after login

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>
Copy after login

就像前面的情况一样,消息的优先级由其在模板中的位置决定。您还可以通过在各个字段中包含自定义错误消息来覆盖模板中提供的通用消息。还可以使用以下代码从单独的文件加载错误消息:

<div ng-messages="formValidation.userPassword.$error">
    <div ng-messages-include="path/to/generic-messages.html"></div>
</div>
Copy after login

仅在需要时显示错误

您可以通过仅在用户在填写表单时实际出错时显示错误消息,使表单更加用户友好。例如,您可以选择仅在用户实际跳过输入元素时显示必填字段错误。

这可以通过使用 ng-showng-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">
Copy after login

这是显示 $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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use CodeIgniter4 framework in php? How to use CodeIgniter4 framework in php? May 31, 2023 pm 02:51 PM

PHP is a very popular programming language, and CodeIgniter4 is a commonly used PHP framework. When developing web applications, using frameworks is very helpful. It can speed up the development process, improve code quality, and reduce maintenance costs. This article will introduce how to use the CodeIgniter4 framework. Installing the CodeIgniter4 framework The CodeIgniter4 framework can be downloaded from the official website (https://codeigniter.com/). Down

How to use Flask-WTF to implement form validation How to use Flask-WTF to implement form validation Aug 03, 2023 pm 06:53 PM

How to use Flask-WTF to implement form validation Flask-WTF is a Flask extension for handling web form validation. It provides a concise and flexible way to validate user-submitted data. This article will show you how to use the Flask-WTF extension to implement form validation. Install Flask-WTF To use Flask-WTF, you first need to install it. You can use the pip command to install: pipinstallFlask-WTF import the required modules in F

Laravel Development: How to validate form requests using Laravel Validation? Laravel Development: How to validate form requests using Laravel Validation? Jun 13, 2023 pm 01:34 PM

Laravel is a popular PHP web development framework that provides many convenient features to speed up the work of developers. Among them, LaravelValidation is a very practical function that can help us easily validate form requests and user-entered data. This article will introduce how to use LaravelValidation to validate form requests. What is LaravelValidationLaravelValidation is La

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

How to handle form validation using middleware in Laravel How to handle form validation using middleware in Laravel Nov 02, 2023 pm 03:57 PM

How to use middleware to handle form validation in Laravel, specific code examples are required Introduction: Form validation is a very common task in Laravel. In order to ensure the validity and security of the data entered by users, we usually verify the data submitted in the form. Laravel provides a convenient form validation function and also supports the use of middleware to handle form validation. This article will introduce in detail how to use middleware to handle form validation in Laravel and provide specific code examples.

PHP form validation tips: How to use the filter_input function to verify user input PHP form validation tips: How to use the filter_input function to verify user input Aug 01, 2023 am 08:51 AM

PHP form validation tips: How to use the filter_input function to verify user input Introduction: When developing web applications, forms are an important tool for interacting with users. Correctly validating user input is one of the key steps to ensure data integrity and security. PHP provides the filter_input function, which can easily verify and filter user input. This article will introduce how to use the filter_input function to verify user input and provide relevant code examples. one,

Form validation and filtering methods in PHP? Form validation and filtering methods in PHP? Jun 29, 2023 pm 10:04 PM

PHP is a scripting language widely used in web development, and its form validation and filtering are very important parts. When the user submits the form, the data entered by the user needs to be verified and filtered to ensure the security and validity of the data. This article will introduce methods and techniques on how to perform form validation and filtering in PHP. 1. Form validation Form validation refers to checking the data entered by the user to ensure that the data complies with specific rules and requirements. Common form verification includes verification of required fields, email format, and mobile phone number format.

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

See all articles