简体   繁体   中英

Angular Error : Displaying error messages for custom Validators

I am trying to add custom validators to a angular form i have created. the validators themselves are working correct but i am now trying to add an error message on the form to state whether the field is incorrect or there is an error.

I have come across the following website ( https://blog.angular-university.io/angular-custom-validators ) where i initially got the validating code from and i have tried to follow the example they use to add error messages.

i have included my html file: `

<div class="container-fluid text-center">
    <form [formGroup]="fg">

        <div class="row">
            <div class="col-3">
                <div class="contactListArea">

                    <h2>Contacts</h2>
                    <ul id="list">
                        <li *ngFor="let contact of contacts;">
                            <button class="btn btn-primary" type="button" (click)="getContact(contact.id)">
                                <span class="name">{{contact.firstName}} {{contact.lastName}} </span>
                            </button>
                        </li>
                    </ul>
                </div>
            </div>

            <div class="col-3">
                <div class="row">
                    <div class="main-contact-list">
                        <div class="form-group mb-3 mr-5 mt-5">
                            <label class="mb-1">First Name</label>
                            <input class="form-control" type="text" class="form-control" [(ngModel)]="contact.firstName"
                                name="Name" formControlName="firstName" placeholder="Enter First Name">
                            <!-- <small *ngIf="firstName.errors?.nameStrength">
                                Your password must have Upper Case starting letter an 3 characters.
                            </small> -->
                        </div>

`

i have also attached the ts file i used to create the validator: `

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export function nameValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {

        const value = control.value;

        if (!value) {
            return null;
        }

        const nameValid = /[A-Z]{1,}[A-Za-z]{2,}/.test(value)
        const noWhite = /^\S*$/.test(value);

        const nameValidNoWhite = nameValid && noWhite

        return !nameValidNoWhite ? { nameStrength: true } : null;
    }
}

`

i have also included the ts file for my component where i actually add the validator to my form:

`

initForm(): void {
    let id = Date.now() * Math.random();
    this.fg = this.fb.group({
      id: [id],
      firstName: ['', [Validators.required, nameValidator()]],
      lastName: ['', [Validators.required, nameValidator()]],
      emailAddress: ['', [Validators.required, Validators.email]],
      address1: ['', [Validators.required]],
      address2: ['', [Validators.required]],
      city: ['', [Validators.required]],
      postCode: ['', [Validators.required, postCodeValidator()]],
    });
  }

`

when i add the error code to the form it breaks the form. the screen shots below show what happens: How the screen should look

what happens when i implement the *ngIf statement: what happens when the ngIf command is used according to the tutorial website

i have followed the example mentioned in the web link and when i add statement and include the *ngIf statement to say that if the input does not meet the requirements then the strength is false and should show the error message. it basically breaks the app.

im not sure whether the first part of the code (this is an example from the website): *ngIf="password.errors?.passwordStrength"

should be the form control name for my chosen input?

so i managed to figure out how to add the error message.

so i have a validator attached to the 'last Name' field which essentially says if it doesnt meet the criteria then it is an error.

in my html template i adding the following piece of code:

<span class="help-block"
*ngIf="fg.get('firstName')?.errors && fg.get('firstName')?.touched">
Your Name must have Upper Case starting letter and 3 characters. </span>

what this code does it basically reference the variable we have assigned for our form group(fg) and then we use the get statement to pull the form control name we have assigned (firstName) to the field we want to work with and we state that if there any errors of if the field has been touched then issue the following error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM