Angular 2 Reactive form make both select dropdowns required if one has had one of its options selected -
i have 2 select dropdowns. both optional fields. need them both required if 1 of 2 has had 1 of options selected. i'm looking everywhere , know custom validator have no idea begin examples online don't come close need.
let assume if enter pin , confirmpin must (vice versa) else no need of required validations both.
code:
this.userform = this.fb.group({ .... .... security: this.fb.group({ pin: [this.securityobj.pin], confirmpin: [this.securityobj.confimrpin] }, {validator: abhimatcher}) });
customvalidator
export const customvalidator= (control: abstractcontrol): { [key: string]: boolean } => { const initaltext = control.get('pin'); const requiredtext = control.get('confirmpin'); if (initaltext || requiredtext) return null; else return { customvalidate: true }; }
html
<form [formgroup]="userform" novalidate (ngsubmit)="onsubmit(userform)"> ..... ..... <input type="password" class="form-group" formcontrolname="pin"> <div *ngif="userform.get('security').haserror('customvalidate') && userform.get('security').get('pin').touched" class="text-danger"> pin required! </div> </div><br /> <div> <label class="center-block">confirmpin:</label> <input type="password" class="form-group" formcontrolname="confirmpin"> </div> <div *ngif="userform.get('security').haserror('customvalidate') && userform.get('security').get('confirmpin').touched" class="text-danger"> pin required! </div> <button type="submit" class="btn btn-default" [disabled]="userform.invalid">submit</button> </form>
Comments
Post a Comment