I have implemented conditional Validation in my Component. I am trying to separate the validation logic from my component to another component/service.

Demo Link : http://StackBlitz%20https://stackblitz.com/edit/angular-amr86r

1

There are 1 best solutions below

1
On

You can easily apply conditional validation using @rxweb/reactive-form-validators. I have applied required validation through both validator as well as decorator based approach. Please refer to the working example.

Using Decorator based approach:

You just need to apply @required() decorator with the condition you want to apply on your model-property.

Here is the complete model code:

import {  required } from   "@rxweb/reactive-form-validators"   

export class UserInfo {

    @required() 
    firstName: string;

    @required({conditionalExpression:'x => x.firstName == "Bharat"' }) 
    lastName: string;

}

Using Validator based approach:

For validator based approach, you just need to mention RxwebValidators.required() with the condition you want to apply on your form-control.

Here is the complete component code:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from "@angular/forms"
import { RxwebValidators } from '@rxweb/reactive-form-validators';

@Component({
    selector: 'app-validator-based-validator',
    templateUrl: './validator-based.component.html'
})
export class ValidatorBasedValidationComponent implements OnInit {
    validatorBasedFormGroup: FormGroup

    constructor(
        private formBuilder: FormBuilder )
    { }

    ngOnInit() {
        this.validatorBasedFormGroup = this.formBuilder.group({
            firstName:['', RxwebValidators.required()],
            lastName:['', RxwebValidators.required({conditionalExpression:'x => x.firstName == "Bharat"' })]
        });
    }
}

Note : if you will use validator approach then, You can create a function in a separate file and use that respective function in the condtional expression property. In anyway, the model file will be separated in decorator based approach.