javascript - 如何使用 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}
解决方案
首先,请考虑使用输入字段。
我建议使用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]
部分将类“错误”添加到标签中。您也可以将其用于您的输入字段。
推荐阅读
- ios - imagePickerController - 选择媒体后没有调用 didFinishPickingMediaWithInfo
- java - 无法从 SQLite 检索简单字符串
- c++ - 如何使用类似 opendir 的函数打开目录,但使用文件系统库?
- php - 在 android 中使用 Socket 跟踪多个用户位置并在客户端应用程序中显示
- numpy - TypeError:无法转换 numpy.object_ 类型的 np.ndarray
- python - 从列表中删除重复的数字
- wpf - 如何将列表的属性与数据网格 WPF 的行索引绑定
- python - ModuleNotFoundError:没有名为“sklearn.compose”的模块
- unity3d - Unity如何在不冻结对象位置的情况下为对象的位置设置动画
- python - 将文件从一个目录移动到多个子文件夹