liveBook · Manning

Validation

As explained in Pro Angular 16

Data validation is the process of checking input data against specified rules for correctness, completeness, or acceptability.

Validation checks form input against rules before the application accepts it. Users can leave fields empty, enter unsuitable values, or submit before a form is complete. Angular can track whether each field—and the form as a whole—satisfies its rules, then use that status to guide submission and feedback. section 13.4.2 section 13.4.3

Build validation into a form in stages:

  • Give each validated input a name, bind it with ngModel, and place it inside a form. Add rules such as required, minlength, or pattern to the input. section 13.4.2
  • Use a template reference such as #name="ngModel" to inspect the field. Its valid, invalid, dirty, and touched properties describe its status; errors identifies failed rules. section 13.4.2
  • Show field messages when they will help: for example, after the field has been edited, or after a submit attempt. Angular also assigns status classes that CSS can use to mark valid and invalid inputs. section 13.4.2 section 13.4.3
  • Reference the form with #form="ngForm" and pass it through ngSubmit. In the handler, accept the data only if form.valid; after a successful submission, reset the form if it will be reused. section 13.4.3
Table 13.4. The built-in Angular validation attributes
Attribute
Description
email
This attribute is used to specify a well-formatted email address.
required
This attribute is used to specify a value that must be provided.
minlength
This attribute is used to specify a minimum number of characters.
maxlength
This attribute is used to specify a maximum number of characters. This type of validation cannot be applied directly to form elements because it conflicts with the HTML5 attribute of the same name. It can be used with model-based forms, which are described later in the chapter.
min
This attribute is used to specify a minimum value.
max
This attribute is used to specify a maximum value.
pattern
This attribute is used to specify a regular expression that the value provided by the user must match.

The built-in rule table distinguishes required values, length and numeric limits, email format, and pattern matching. Its maxlength entry also notes a limitation for direct form-element use. section 13.4.2

A product-name field

A product form binds an input to newProduct.name and gives it the name "name". Its required, minlength="5", and pattern="^[A-Za-z ]+$" rules reject an empty, short, or nonmatching value. A message list can inspect name.errors to explain which rule failed, including the required character count for minlength. section 13.4.2

Listing 13.21. Performing validation in the template.html file in the src/app folder
<div class="p-2">
    <form #form="ngForm" (ngSubmit)="submitForm(form)">

        <div class="bg-danger text-white p-2 mb-2"
                *ngIf="formSubmitted && form.invalid">
             There are problems with the form
        </div>

        <div class="form-group">
            <label>Name</label>
            <input class="form-control"
                name="name"
                [(ngModel)]="newProduct.name"
                #name="ngModel"
                required
                minlength="5"
                pattern="^[A-Za-z ]+$" />
            <ul class="text-danger list-unstyled mt-1"
                    *ngIf="(formSubmitted || name.dirty) && name.invalid">
                <li *ngFor="let error of getValidationMessages(name)">
                    {{error}}
                </li>
            </ul>        
        </div>
        <button class="btn btn-primary mt-2" type="submit">
            Create
        </button>
    </form>
</div>

The form template connects ngSubmit to submitForm(form). It displays a form-wide warning after an invalid submission while retaining messages beside fields that are invalid and either edited or submitted. section 13.4.3

For a larger form, collect errors from form.controls into a summary instead of requiring users to find each problem unaided. CSS can target ng-submitted together with ng-invalid or ng-valid so untouched fields receive feedback after submission. In a checkout flow, the same validity check prevents saving an order until its required details are supplied. section 13.4.3 section 13.4.4 section 6.5.2

How Pro Angular 16 covers it

How deep it goes
Works through field rules, status, error messages, whole-form checks, summaries, and reset; identifies custom rules without implementing them here.
Examples
Uses a product-entry form with name, category, and price fields, plus an order checkout form.
What it assumes
Builds on HTML forms, event bindings, two-way binding, and ngModel while introducing validation through a single input.
What you can do after
Apply it via Angular forms to reject invalid submissions and show field-level or form-wide feedback.
How it connects
Connects HTML forms to event bindings, two-way binding, ngModel, NgForm, template references, and CSS status classes.

Also explained in

Compare how 30 books explain validation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.