<div class="col-md-6">
<div class="form-group">
<h6>Email Address</h6>
<input type="text" class="form-control" name="email" formControlName='Bemail' required>
<div [hidden]="BusinessInfoForm.controls.Bemail.valid || (BusinessInfoForm.controls.Bemail.pristine && !submitted)" >
<p class="text-danger" [hidden]="!BusinessInfoForm.controls.Bemail.errors.required">mailAddressis required.</p>
<p class="text-danger" [hidden]="!BusinessInfoForm.controls.Bemail.errors.incorrectMailFormat">Email format is invalid.</p>
</div>
</div>
</div>
Component code:
this.BusinessInfoForm=this.BI.group({
'BusinessName':['', Validators.required ],
"Bphone":['', Validators.required ],
"CBphone":['', Validators.required ],
"Bemail": ['',Validators.compose([Validators.required, GlobalValidator.mailFormat])],
"CBemail":['', Validators.required ],
"BzipCode": ['', Validators.required ],
"Bcity": ['', Validators.required ],
"Bstate": ['', Validators.required ],
"Bstreet1": ['', Validators.required ],
"Bstreet2": ['', Validators.required ],
'FirstName':['', Validators.required ],
"LastName":['', Validators.required ],
"zipcode": ['', Validators.required ],
"city": ['', Validators.required ],
"state": ['', Validators.required ],
"checkboxvalue":['',Validators.required],
"streetAddress1": ['', Validators.required ],
"streetAddress2": ['', Validators.required ],
},{validator:matchingValidator('Bemail','CBemail')})
}
Global Validator Class:
import { NG_VALIDATORS, AbstractControl, ValidatorFn, Validator,FormControl } from '@angular/forms';
export class GlobalValidator{
static mailFormat(control: FormControl): ValidationResult {
console.log(control.value);
var EMAIL_REGEXP = /^(([^<>()\[\]\\.,;:\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 (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
return { "incorrectMailFormat": true };
}
return null;
}
}
interface ValidationResult {
[key: string]: boolean;
}
我在这里做错了什么。一旦验证了电子邮件,它就会抛出错误,说明无法读取null所需的属性。当我返回false而不是null时,电子邮件仍处于无效状态。因此,表单正在验证。感谢。