问题
I have a FormGroup that is composed by 3 input fields: reservationCode, secretCode and barcode.
The field barcode is simply reservationCode + '-' + secretCode. (this because barcode is a field that can be found in text and usable with copy+paste function)
now, the button that uses these fields have to be active only if barcode has value or if reservationCode and secretCode has value.
the logic should be something like: "barcode || reservationCode && secretCode"
here's the code of the formGroup i have in my .ts:
this.voucherVerifyUserDataFormGroup = formBuilder.group({
reservationCode: [''],
secretCode: [''],
barcode: ['']
});
I don't know how to manage formControl Validators and if i have to create a custom one.
回答1:
Try this :
this.voucherVerifyUserDataFormGroup.valueChanges.subscribe((form : any) =>{
//check your condition :
if(form.barcode != '' || (form.reservationCode != '' && form.secretCode != '')){
this.voucherVerifyUserDataFormGroup.setErrors(null);
}
else
{
this.voucherVerifyUserDataFormGroup.setErrors({ 'invalid': true});
}
})
回答2:
You can achieve using *ngIf/disabled.
<input type="button" *ngIf="isDataPresent" value="Paste">
Component:
get isDataPresent(){
return this.voucherVerifyUserDataFormGroup.get('barcode').value || (this.voucherVerifyUserDataFormGroup.get('reservationCode').value && this.voucherVerifyUserDataFormGroup.get('secretCode').value);
}
来源:https://stackoverflow.com/questions/53260398/formgroup-validation-in-exclusive-or