在Angular反应性表单中具有必填项的电子邮件验证

时间:2018-08-19 12:37:00

标签: javascript angular validation email angular-reactive-forms

使用Angular反应形式来验证电子邮件。

我添加了Validators Required和Validators Email,但其显示均如下图所示。我只希望一次显示一个错误。

enter image description here

HTML代码:

<form [formGroup]="NamFomNgs">

    <label>Email : 
        <input type="email" name="MylHtm" formControlName="MylNgs">
    </label><br>
        <div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['MylNgs'].touched || NamFomNgs.controls['MylNgs'].dirty) && 
            !NamFomNgs.controls['MylNgs'].valid">
            <span *ngIf="NamFomNgs.controls['MylNgs'].errors.required">This field is required</span>
            <span *ngIf="NamFomNgs.controls['MylNgs'].errors.email">Enter valid email</span>
        </div><br>

    <button [disabled]="!NamFomNgs.valid">Submit</button>
</form>

打字稿代码:

NamFomNgs:FormGroup;

constructor(private NavPkjVaj: ActivatedRoute, private HtpCncMgrVaj: HttpClient,private FomNgsPkjVaj: FormBuilder)
{
    this.NamFomNgs = FomNgsPkjVaj.group(
        {
            MylNgs:[null,Validators.compose([
                Validators.required,
                Validators.email ])]
        });
}

我觉得这是一个成角度的错误。

1 个答案:

答案 0 :(得分:1)

您可以创建公共组件以显示验证消息:

custom-validation-with-error-message

HTML:

<div *ngIf="errorMessage !== null">
    {{errorMessage}}
</div>

constrol-message.component.ts:

import { OnInit } from '@angular/core';
import { Component, Input } from '@angular/core';
import { FormGroup, FormControl, AbstractControl } from '@angular/forms';

import { CustomValidationService } from '../custom-validation.service'


export class ControlMessageComponent implements OnInit {

  ngOnInit() {

  }
  @Input() control: FormControl;

  constructor() { }

    /**
     * This method is use to return validation errors
     */
  get errorMessage() {
    for (let propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
        return CustomValidationService.getValidatorErrorMessage(this.getName(this.control), propertyName, this.control.errors[propertyName]);
      }
      if (this.control.valueChanges) {
        return CustomValidationService.showValidatorErrorMessage(propertyName, this.control.errors[propertyName])
      }
    }
    return null;
  }

    /**
     * This method used to find the control name
     * @param control - AbstractControl
     */
  private getName(control: AbstractControl): string | null {
    let group = <FormGroup>control.parent;

    if (!group) {
      return null;
    }
    let name: string;
    Object.keys(group.controls).forEach(key => {
      let childControl = group.get(key);
      if (childControl !== control) {
        return;
      }
      name = key;
    });
    return name;
  }
}