1. 将表单的方法移动到单独的ts文件夹中
2. code
export function mobileValidator(control: FormControl): any { const myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; const valid = myreg.test(control.value); console.log('mobile result: ' + valid); return valid ? null : {mobile: true}; } export function equalValidator(group: FormGroup): any { const password: FormControl = group.get('password') as FormControl; const pconfirm: FormControl = group.get('pconfirm') as FormControl; const valid: boolean = password.value === pconfirm.value; console.log('password equal: ' + valid); return valid ? null : {equal: {descerr: '密码和确认密码不匹配'}}; }
3. html
<form [formGroup]="formModel" (submit)="submit()"> <div> 用户名:<input type="text" formControlName="username"> <div [hidden]="!formModel.hasError('required','username')"> 用户名是必填项 </div> <div [hidden]="!formModel.hasError('minlength','username')"> 用户名是最小长度为6 </div> 电话:<input type="text" formControlName="mobile"> <div [hidden]="!formModel.hasError('mobile','mobile')"> 请输入正确的手机号 </div> <div formGroupName="passwordsGroup"> 密码:<input type="password" formControlName="password"> 确认密码:<input type="password" formControlName="pconfirm"> <div [hidden]="!formModel.hasError('minlength',['passwordsGroup', 'password'])"> 密码最小长度为6 </div> <div [hidden]="!formModel.hasError('equal','passwordsGroup')"> {{formModel.getError('equal','passwordsGroup')?.descerr}} </div> </div> </div> <div><button type="submit">保存</button></div> </form>
4. 控制器
formModel: FormGroup; constructor(private http: Http, fb: FormBuilder) { this.formModel = fb.group({ username: ['', [Validators.required, Validators.minLength(6)]], mobile: ['', mobileValidator], passwordsGroup: fb.group({ password: ['', Validators.minLength(6)], pconfirm: [''] }, { validator: equalValidator} ), }); } submit() { const isValid: boolean = this.formModel.get('username').valid; console.log('username: ' + isValid); const errors: any = this.formModel.get('username').errors; console.log('username errors' + JSON.stringify(errors)); if ( this.formModel.valid) { console.log(this.formModel.value); } }
5. 状态字段
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!