简体   繁体   中英

Angular2 Forms Validation Error messages

I am new to Angular and JavaScript overall, I'm trying to add messages when user input is wrong using the Materialize library (the data-error attribute). So my html component looks like this:

            <input
                    type="text"
                    id="username"
                    formControlName="username"
                    [class.valid]="username?.valid && username.dirty"
                    [class.invalid]="!username?.valid && username.dirty && !username.pending"
            >
            <label for="username"
                   data-error="ERROR_MESSAGE" // <-- this is what I need to work
            >Username</label>

I want to change the data-error attribute depending on the error present. Right now it will print "ERROR_MESSAGE" on any error present. I tried writing a function and binding it with [attr.data-error] like this:

    displayUsernameErrorMessage() {
    let message = '';
    let usernameError = this.username.errors;
    if(usernameError.pattern){
        message = "Invalid Username"
        console.log(usernameError);
    }
    else {
        return null;
    }
}

I think I'm doing a really bad job with this, the function logs like 10 times in the console and it's a poor solution. Any ideas on how to make it work better are greatly appreciated!

EDIT 1: Additional info is that I want to display different messages depending on the error. So if I get an error from the Validator.pattern - I want the message to be something like "Invalid username" or if it's from Validators.required - "Please insert a username", something like that.

That's how I'm doing it (adapted to your Exemple):

<form name="nameForm" [formGroup]="nameForm">
<fieldset>
        <label for="username">Username</label>
        <input
          required
          id="username"
          formControlName="username"
        >
        <span
          class="text-danger"
          [hidden]="nameForm.controls.name.valid || itemForm.controls.name.pristine"
        >
          <small>{{'Please enter your name'}}</small>
        </span>
      </fieldset>
</form>

In your TS file :

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

export class InputComponent  {   
   public nameForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {

  this.nameForm = this.formBuilder.group({
  username:    new FormControl('', Validators.required),
   });
  }
//... codes..
}

Where you can customize the text-danger in your CSS (or any alternative) file

I needed to do something like this as well so I ended up writing a directive that can be placed on <label> elements.

In your example it would look like this:

<label for="username" errorMessageForFormControl>Username</label>
<input required id="username" formControlName="username">

I wanted to avoid repeating the control name twice so the directive looks at the value of the for attribute and finds the control from that. If your FormControls and <input> field IDs happen to not match up you can set it yourself.

<label for="somethingDifferent" errorMessageForFormControl="username">Username</label>
<input required id="somethingDifferent" formControlName="username">

The directive ended up looking like this:

import { Directive, Host, HostBinding, Input, Optional, OnInit, SkipSelf } from '@angular/core';
import { AbstractControl, ControlContainer } from '@angular/forms';

@Directive({
    selector: '[errorMessageForFormControl]'
})
export class errorMessageDirective implements OnInit {
    @HostBinding('class.validation-error') validationErrorCssClass = false;
    @HostBinding('attr.data-error') errorMessage: string = null;

    @Input() public errorMessageForFormControl: string;
    @Input() public for: string;

    private ctrl: AbstractControl = null;

    constructor(
        @Optional() @Host() @SkipSelf()
        private controlContainer: ControlContainer
    ) { }

    public ngOnInit(): void {
        if (!this.controlContainer) {
            return;
        }

        const formControlName = this.errorMessageForFormControl || this.for;
        if (formControlName) {
            this.ctrl = this.controlContainer.control.get(formControlName);
        }

        if (this.ctrl) {
            this.ctrl.statusChanges.subscribe(statusText => {

                if (statusText === 'INVALID') {
                    // invalid
                    const errors = this.ctrl.errors;
                    if (errors) {
                        const errKey = Object.keys(errors)[0];
                        const errVal = errors[errKey];
                        this.errorMessage = errVal === true ? errKey : errVal;
                    } else {
                        this.errorMessage = 'validation failed';
                    }

                    this.validationErrorCssClass = true;
                } else {
                    // valid
                    this.errorMessage = null;
                    this.validationErrorCssClass = false;
                }
            });
        }
    }
}

And you can refer to the data-error attribute in some css

[data-error].validation-error::after {
    color:red;
    content: attr(data-error);
    opacity: 0.8; 
    font-weight: bold;
    font-style: italic;
    font-size: 0.75em;
    margin-right: 0.25em;
    z-index: 99;

    float: right;
    transform: translateY(85%);
}

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