我有提交电子邮件的表单,我想添加验证,因此不能为empyt(必需),不能为无效的电子邮件(例如juventusSignedCr7@4.4,
等),但是当我向其中添加电子邮件(例如neymarPleaseStopeDiving
)时我的输入并单击提交,没有错误返回,并且仅在我提交空输入时才提交数据,我得到了错误消息。电子邮件为必填
这是我所做的:
更新
component.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>
问题
我的代码有什么问题?请在这里帮助新手,谢谢
答案 0 :(得分:3)
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*$"
将确保有一个@和一个。然后是一个字符串。
答案 1 :(得分:2)
You also can use a regular expresion for the email field, something like this, in your input tag
<input type="email" class="form-control info" placeholder="Email" formControlName="email" (ngModelChange)="onChange($event)">
like this you call a function each time a user type inside, then in your Ts file, you declare the function that you put inside your input tag in your html
onChange(newValue) {
const validEmailRegEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (validEmailRegEx.test(newValue)) {
this.validEmail = true;
}else {
this.validEmail = false;
}
}
Just dont forget to declare the variable validEmail
on the top of your file
validEmail:boolean = false
the constant validEmail
is where you declare the regex expresion, the one that i put i really good for email validation,the method test
is where you compare the expresion with the string, the method returns true or false
After that in your html button tag goes something like this.
<button type="submit" class="btn btn-primary btn-block logBtn" [disabled]="!validEmail">ACCEDER</button>
i like this way because i can have full control of what i want in each input tag
答案 2 :(得分:1)
我看到您正在使用FormGroup,我所做的和对我有用的工作是在控制器中创建FormGroup时添加一个验证
FormGroup({
email: new FormControl('', [Validators.required, Validators.email])
})
此验证器已绑定到[formGroup]="angForm"
您还可以创建自定义验证器
import { AbstractControl } from '@angular/forms';
export function ValidateUrl(control: AbstractControl) {
if (!control.value.startsWith('https') || !control.value.includes('.io')) {
return { validUrl: true };
}
return null;
}
/**
a easy validator for an email could be something like this
let a = "adas@sdfs.com"
let b = a.split('@')
if(b.length == 2){
//ok
let c = b[1].split('.')
if(c.length >= 1){
//ok
//a have <something>@<something>.<something>
}
}
**/
并在控制器中导入验证器
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ValidateUrl } from './validators/url.validator';
@Component({
// ...
})
export class AppComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
userName: ['', Validators.required],
websiteUrl: ['', [Validators.required, ValidateUrl]],
});
}
}
从here
获得了示例