<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 时,电子邮件仍处于无效状态。因此,表单正在得到验证。谢谢。