问题
I am wanting to check if the values of two fields are the same, these fields must be passed by parameters to the validation function, I am doing this, the problem is that it can not get the value of the field, it appears null, as Can I get the values correctly and dynamically?
My form builder, I'm using the match function to check the cell_phone and confirmation fields.
this.recharge = this.formBuilder.group({
cell_phone: ['', Validators.required, Validations.match('cell_phone', 'cell_phone_confirmation')],
cell_phone_confirmation: ['', [Validators.required]],
value: ['', Validators.required],
operator_id: ['', Validators.required]
});
In my function, console log is null:
static match(field1: string, field2: string){
return (group: FormGroup) => {
console.log(group.get(field1));
}
}
回答1:
You need to create a custom formGroup validator to check the value of the form controls values and check theme
this.recharge = formBuilder.group({
cell_phone: ['', Validators.required],
cell_phone_confirmation: ['', Validators.required],
},
{
validator: checkMatchValidator('cell_phone', 'cell_phone_confirmation')
}
);
Custom Validator function
export function checkMatchValidator(field1: string, field2: string) {
return function (frm) {
let field1Value = frm.get(field1).value;
let field2Value = frm.get(field2).value;
if (field1Value !== '' && field1Value !== field2Value) {
return { 'notMatch': `value ${field1Value} is not equal to ${field2}` }
}
return null;
}
}
stackblitz demo 🚀🚀
回答2:
You can try like this.
this.recharge = this.formBuilder.group({
cell_phone: ['', Validators.required],
cell_phone_confirmation: ['', [Validators.required]],
value: ['', Validators.required],
operator_id: ['', Validators.required]
},{ validator: Validations.match });
static match(c: AbstractControl){
const cellphone = c.get('cell_phone');
const cellphoneconfirm = c.get('cell_phone_confirmation');
}
回答3:
I'd use root property to access to cell_phone_validator
control
cell_phone: ['', [Validators.required, this.cellPhoneValidator]]
private cellPhoneValidator(control: AbstractControl) {
if (control.root.get('cell_phone_confirmation') {
return control.root.get('cell_phone_confirmation').value !== control.value ?
{ cellPhoneValidator: { value: control.value } } : null;
}
}
EDIT : you want to use it for any field, so let's make it general
cell_phone: ['', [Validators.required, Validations.matchValidator('cell_phone_confirmation')]],
cell_phone_confirmation: ['', [Validators.required, Validations.matchValidator('cell_phone')]]
private matchValidator(controlValidationName: string): ValidatorFn {
return (control: AbstractControl) => {
const controlValidation = control.root.get(controlValidationName);
if (!controlValidation) {
return null;
}
return controlValidation.value !== control.value ?
{ matchValidator: { value: control.value } } : null;
}
}
来源:https://stackoverflow.com/questions/53746285/how-to-check-if-two-fields-are-equal-in-angular-ionic