1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| // html <form [formGroup]="customizeForm"> <ul> <li> <label>姓名:</label> <input type="text" name="name1" formControlName="name1"> <p style="display: inline;" *ngIf="customizeForm.controls.name1.invalid">姓名错误</p> </li>
<li> <label>电话:</label> <input type="text" name="tel1" formControlName="tel1"> <p style="display: inline;" *ngIf="customizeForm.controls.tel1.invalid">{{this.customizeForm.controls.tel1.errors.errorMsg}}</p> </li>
<li> <label>邮箱:</label> <input type="text" name="email1" formControlName="email1"> <p style="display: inline;" *ngIf="customizeForm.controls.email1.invalid">{{this.customizeForm.controls.email1.errors.errorMsg}}</p> </li> </ul> </form>
// ts customizeForm = new FormGroup({ name1: new FormControl("", [Validators.minLength(4), Validators.maxLength(10), Validators.required]), tel1: new FormControl("", validateTel), email1: new FormControl("", validateEmail), }) // validattion.ts const TEL_REGEXP = new RegExp("1[0-9]{10}"); const EMAIL_REGEXP = new RegExp("[a-z0-9]+@[a-z0-9]+.com"); export function validateTel(c: FormControl){ return TEL_REGEXP.test(c.value) ? null : { errorMsg: '电话错误', } }
export function validateEmail(c: FormControl){ return EMAIL_REGEXP.test(c.value) ? null : { errorMsg: '邮箱错误', } }
|