Conditional Validation In Angular Using RxWeb
Tags: typescript, webdev, rxweb, angular
Published: 2020-04-04 12:35:10

Forms require a lot of validation scenarios in which one of the most common needed is conditional validation which is used in very front end application.

When it comes to applying conditional validation angular it requires a custom function having a lot of if and else conditions with fetching the formControl value and checking it!!😥

But Not Always🙂, Conditional validation is possible with a simpler, neater and lesser code with just using one property during assigning the validator during the formControl initialization itself

This is possible with the help of [@rxweb/reactive-form-validators](https://www.npmjs.com/package/@rxweb/reactive-form-validators). This package provides more than 50 in-built validators with every necessary property used to validate the form.

Here I have a project registration form in which there are two scenarios, project registration can be done individually or by group name, incase of individual project fullName field should be required and incase of team project teamName should be required. This is how conditional validation is done.

   ![Conditional Validation](https://dev-to-uploads.s3.amazonaws.com/i/4qxpdctjlh5uvyesvpna.gif)

The condition is applied using `conditionalExpression` property which can be set as `Function` or string.

The conditionalExpression as function can be written as:

```js
 RxwebValidators.required({conditionalExpression:(x,y) => x.projectType == "Individual"  })
```

The conditionalExpression as string can be written as :

```js
RxwebValidators.required({conditionalExpression:'x => x.projectType == "Team"' })
```
> Along with required validation, conditional validation can be applied to all the validators available in the package using `conditionalExpression` property.

The complete component code is as below:
```js
export class ProjectComponent implements OnInit {
    userFormGroup: FormGroup
Types = ["Team","Individual"];
	constructor(
        private formBuilder: FormBuilder )
	{ }

    ngOnInit() {
        this.userFormGroup = this.formBuilder.group({
            projectType:[''], 
            teamName:['', RxwebValidators.required({conditionalExpression:'x => x.projectType == "Team"' })], 
            fullName:['', RxwebValidators.required({conditionalExpression:(x,y) => x.projectType == "Individual"  })], 
        });
    }
}

```

The Html code is as below:
```js
<div>
  <form  [formGroup]="userFormGroup">
      <div class="form-group">
      <label>Project</label>
      <select formControlName="projectType" class="form-control">
		<option [value]="item" *ngFor="let item of Types">{{item}}</option>
      </select>
      <small class="form-text text-muted">Based on selection of project type conditional validation is applied<br/></small>
    </div>
    <div class="form-group">
      <label>Team Name</label>
      <input type="text" formControlName="teamName" class="form-control"  />
      
	<small class="form-text text-danger" *ngIf="userFormGroup.controls.teamName.errors">{{userFormGroup.controls.teamName.errors.required.message}}<br/></small>
    </div>
    <div class="form-group">
      <label>Full Name</label>
      <input type="text" formControlName="fullName" class="form-control"  />
    
	<small class="form-text text-danger" *ngIf="userFormGroup.controls.fullName.errors">{{userFormGroup.controls.fullName.errors.required.message}}<br/></small>
    </div>
    <button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
  </form>
</div>

```

The complete example on [stackblitz](https://stackblitz.com/edit/angular-7f9ktz?file=src/app/required-conditional-expression.component.html) Feel free to share your comment and inputs.