当电子邮件无效时,我想用红色显示数据。
我没有。在数据中,有一些电子邮件ids没有被验证。我只使用动态类。
//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}
发布于 2020-06-16 10:36:03
你没有正确地使用regex。看看敬这位医生。
您可以创建一个简单的函数来测试您的电子邮件并返回一个布尔值。
组件ts文件:
public isValidEmail(email: string): boolean {
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email);
}
html文件:
<span [ngClass]="{'redClass': isValidEmail(data?.email_id)}">{{ data?.email_id }}</span>
发布于 2020-06-16 10:38:11
首先,请考虑使用输入字段代替。
我建议使用来自https://angular.io/guide/forms的https://angular.io/guide/forms。
它将帮助您使用一个精益的模板,并使验证更加容易。
可能看起来像:
// 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,
])
]
});
在这里,名为“FormGroup”的contactForm包含一个名为"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>
这里的重要部分是连接到ts验证的formControlName和formGroup。
部件class.error将类“错误”添加到标签中。您也可以将其用于输入字段。
https://stackoverflow.com/questions/62406231
复制相似问题