javascript - 在角度 5 中验证同一字段中的电子邮件和电话号码
问题描述
我正在使用 Angular 6,并且我的登录表单与 Gmail 相同。喜欢的用户可以输入电子邮件或电话号码。所以我想在客户端验证两者。我将在 laravel php 的服务器端做。请用最好的方法给我建议。
解决方案
在 Angular 4+ 中,对于客户端验证,请使用反应式表单。
在您的 html 中使用表单
<form [formGroup]="login_form" (submit)="submitForm()">
<input class="form-control" type="email" placeholder="Enter email" formControlName="email" />
<span class="text-danger" *ngIf="login_form.controls['email'].hasError('required') && (login_form.controls['email'].dirty || login_form.controls['email'].touched)">Email address is required</span>
<span class="text-danger" *ngIf="login_form.controls['email'].hasError('email') && (login_form.controls['email'].dirty || login_form.controls['email'].touched)">Please enter valid email address</span>
<input class="form-control" type="password" placeholder="Enter Password" formControlName="password" />
<span class="text-danger" *ngIf="login_form.controls['password'].hasError('required') && (login_form.controls['password'].dirty || login_form.controls['password'].touched)">Password is required</span>
<button class="btn btn-block btn-primary mt-lg" type="submit">Login</button>
</form>
在您的组件中使用以下代码
// First install this package using below cli command
// npm install ng2-validation --save
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
export class YourComponent {
public login_form: FormGroup;
public submitForm(){
if (this.login_form.valid) {
// You will get form value if your form is valid
var formValues = this.login_form.value;
....
} else {
// For Angular 4,5.
for (let v in this.login_form.controls) {
this.login_form.controls[v].markAsTouched();
}
// For Angular 6+ versions.
this.login_form.markAllAsTouched();
}
}
constructor(fb: FormBuilder) {
this.login_form = fb.group({
'email': [null, Validators.compose([Validators.required, CustomValidators.email])],
'password': [null, Validators.required],
});
}
StackBlitz 测试:Stackblitz
推荐阅读
- assembly - 代码在汇编中给我一个无限循环?
- powershell - Powershell Foreach 循环遍历 API 输出并逐行显示变量值
- c++ - 在 char 或 wchar_t 中分配一个数字与广义转义序列以获取符号(对于 char 来说太大)
- elasticsearch - 为某个字段创建具有搜索权限但没有读取权限的角色
- c# - 如何防止继承控件的组件出现在 Visual Studio 属性窗格中进行编辑?
- arrays - 一个包含 bash 中的子字符串的字符串 - 不工作
- swift - 如何在 Swift 中只隐藏键盘而不是 inputAccessoryView
- node.js - 如何使用 elemMatch
- c - 在 c 中搜索 char* 以查找 char* 数组的成员
- python - 如何读取带有 .zip 扩展名的 URL 并获取文件 .txt 并将其保存在目录中?