首页 > 解决方案 > 如何使用 ngClass 添加带有模式验证的验证电子邮件

问题描述

当电子邮件无效时,我想以红色显示数据。

我没有。的数据,其中一些电子邮件 ID 未经过验证。我只使用了动态类。

//ts file

email_regx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

if (this.data.email_id) {
   this.email_regx = true;
} else {
  this.email_regx = false;
}

//html file
<span [ngClass]="{'redClass': email_regx}">{{ data?.email_id }}</span>

//css
  .redClass{ color: red}

标签: javascriptregexangulartypescript

解决方案


首先,请考虑使用输入字段。

我建议使用Angular Forms的FormBuilder。 它将帮助您使用精益模板并使验证变得更加容易。

可能看起来像:

// TS
contactForm: FormGroup;

constructor() {
    this.contactForm = this.formBuilder.group({
        email: [
            '',
            Validators.compose([
                Validators.pattern('^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$'),
                Validators.required,
            ])
        ]
    });

此处称为“contactForm”的 FormGroup 包含一个称为“email”的输入字段。验证适用于您的电子邮件。

// Template
<form id="contactForm" [formGroup]="contactForm">
    <ion-item lines="none" class="list-item">
        <div>
            <ion-label position="stacked"
                       [class.error]="contactForm.controls.email.value != undefined && !contactForm.controls.email.valid">
                E-Mail *
            </ion-label>
            <ion-input id="email" type="email" formControlName="email"></ion-input>
        </div>
    </ion-item>
</form>

这里重要的部分是formControlName[formGroup]以连接到您的 ts 验证。[class.error]
部分将类“错误”添加到标签中。您也可以将其用于您的输入字段。


推荐阅读