FormGroup validation in “exclusive or”

馋奶兔 提交于 2019-12-13 05:50:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!