angular - 带有引导程序 4 的 Angular 6 - 表单验证电子邮件
问题描述
我有提交电子邮件的表单,我想添加验证,因此不能为空(必需),不能是无效的电子邮件,例如juventusSignedCr7@4.4,
等,但是当我将电子邮件添加neymarPleaseStopeDiving
到我的输入并单击提交时,不会返回错误并提交数据,只有当我提交空输入时,我才会收到错误消息。电子邮件是必需的
这是我所做的:
更新
组件.ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
...............
export class AboutComponent implements OnInit {
angForm: FormGroup;
constructor(private flashMessages: FlashMessagesService,
private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
email: ['', Validators.required]
});
}
HTML
<form [formGroup]="angForm" novalidate class="form-element">
<div class="form-group form-element_email">
<input type="email" class="form-control" name="email" formControlName="email" #email />
</div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['email'].errors.required">
Email is required.
</div>
<div class="form-group">
<button (click)="addReview(email.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary form-element_btn">Book</button>
</div>
</form>
问题
我的代码有什么问题?请在这里帮助新手,谢谢
解决方案
Angular 6 提供输入验证器,如电子邮件和必需。
我通常不希望允许me@home
格式并总是期望 TLD(如 .com、.net、.org 等)。除了角度email
验证器之外,我还添加了我的正则表达式pattern
以使其工作。
<input type="email" name="email" #emailField="ngModel" pattern="^\S*[@]\S*[.]\S*$" email required />
<div class="help-block m-1" *ngIf="!emailField.valid && (emailField.touched || emailField.dirty)">
<small>Invalid Email</small>
</div>
email
将实现 Angular 的默认电子邮件验证器。
required
将使该字段成为必填字段。
pattern="^\S*[@]\S*[.]\S*$"
将确保有一个 @ 和一个 . 后跟一个字符串。
推荐阅读
- android - AndroidManifest 权限限制
- pandas - 循环遍历数据框并过滤它的更快方法?
- javascript - 该函数的正确打字稿类型是什么
- java - Wicket 9:用户在部署后首次访问某个页面时强制重新登录
- javascript - 如何使用 React Native 和 AWS 确保每次都导入我的个人资料信息?
- responsive-design - 如何使我的网站对每台设备都完全响应?
- ruby-on-rails - 这个表的索引在哪里
- javascript - iOS Web 应用程序在切换到银行 ID 时失去连接
- python - Python关闭证书验证
- python - 如何从字典中打印出格式良好的表格