基礎表單控制
表單驗證
在[{ value: '', disabled: false }, []]
後面的[]中能放validator
import { Validators } from '@angular/forms';
import { MyValidators } from 'src/app/shared/validators.module';
...
constructor(
private fb: FormBuilder,
) {}
...
form = this.fb.group({
type: [{ value: '', disabled: false }, [Validators.required, Validators.maxLength(9), Validators.minLength(8), MyValidators.type()]],
dateStart: [{ value: '', disabled: false }, []],
dateEnd: [{ value: '', disabled: false }, []],
});
客製化Validators
export function type(): ValidatorFn {
return (control: FormControl) => {
if (control?.value === null || control?.value === '') {
return null;
}
const regex = /^[A-Za-z0-9]+$/g;
if (!control.value.toString().match(regex)) {
return {
errMsg: 'error'
};
}
return null;
};
}
對整個表單做驗證
對表單的dateStart , dateEnd 做驗證
form = this.fb.group({
type: [{ value: '', disabled: false }, [Validators.required, Validators.maxLength(9), Validators.minLength(8), MyValidators.type()]],
dateStart: [{ value: '', disabled: false }, []],
dateEnd: [{ value: '', disabled: false }, []],
},{
validators: [MyValidators.dateRange('dateStart', 'dateEnd', 0)]
});
欄位做連動驗證
1.第一種 訂閱欄位valueChange修改驗證規則
2.第二種 html的 (onChange)="changefunction()" 做驗證規則修改
小陷阱 addValidators removeValidators 要記得 updateValueAndValidity
ngOnInit(): void {
this.form.get('type').valueChanges.subscribe(type => {
if(type === 'animate'){
dateStart.addValidators(MyValidators.dateStart);
dateStart.removeValidators(MyValidators.dateStart);
} else{
dateEnd.addValidators(MyValidators.dateEnd);
dateEnd.removeValidators(MyValidators.dateEnd);
}
});
this.editForm.get('dateStart').updateValueAndValidity();
this.editForm.get('dateEnd').updateValueAndValidity();
}
setValue vs patchValue
this.form.patchValue(this.data) 對整個表單做賦值
this.form.get('type').setValue(type?.value); 對單一欄位做賦值
disable
this.form.get('type').disable 要注意會讓你
this.form.get('type').value 拿不到值
要改用this.form.get('type').getRawValue()