search
HomeWeb Front-endJS TutorialAngularJS form validation using ngMessages

AngularJS form validation using ngMessages

Sep 01, 2023 pm 10:05 PM
angularjsform validationngmessages

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>

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:

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>

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-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">

这是显示 $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
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor