Codementor Events

Power of RxWebValidators

Published Jul 24, 2020Last updated Jan 19, 2021
Power of RxWebValidators

Here we discuss the simplest way to apply validations in angular validations Angular validations are not just about inbuilt and custom validations, some complex forms require a lot of other validation scenarios such as conditional validation. In most of the cases the validation consume of a lot of custom business logic which results into hefty code and reduction of scalability

Here is how performing validations can be performed in a very intuitive, simple and ascendible way. In this article i will show some of the most useful cases of validations in angular reactive forms which can be now done easy...

Conditional Validation

We come across through a lot of use cases when we need to apply validation based upon some user input value. Lets understand the difference between with and without RxWebValidators

Without RxWebValidators

  this.personForm = this.formBuilder.group({
    firstName : ['', Validators.required],
    lastName : ['', conditionalValidator(
      (()=> this.isValidationForLastName === true),
      Validators.required
    )]
  })

  function conditionalValidator(condition: (()=> boolean), validator : ValidatorFn): ValidatorFn {
    return (control : AbstractControl):{[key:string]:any} => {
      if(! condition()){
        return null;
      }
      return validator(control);
    }
  }

With RxWebValidators

he condition is applied during the initialization of the formControl using conditionalExpression property.
Example : open

It requires creation of a custom function for the application of the condition and using it at the time of formControl initialization.

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

Unique Validation

This approach is to unique value validation on FormControl inside the FormArray.

Without RxwebValidators

uniqueValidator(control: AbstractControl) {
      const name = control.get('name').value;
  

    if (control.get('name').valid) {
      const isNameUnique = this.companies.map(company => company.name).some(value => value === name);

      if (!isNameUnique) {
        control.get('name').setErrors({unavailable: true});
      }
    }
    }

    this.companyFormGroup = this.fb.group({
      name: [null, Validators.required],
      emailAddress: [null, Validators.compose([Validators.required, Validators.email])]
    }, {validator: this.uniqueValidator.bind(this)});

With RxwebValidators

The simplest approach towards performing unique validation is given by RxWebValidators.
Example : open

this.employeeFormGroup = this.formBuilder.group({
  fullName: [''],
  skills: this.formBuilder.array([
    this.getSkillFormGroup()
  ])
});
}

addSkill(){
  let skillsArray = <FormArray>this.employeeFormGroup.controls.skills;
  skillsArray.push(this.getSkillFormGroup());
}

getSkillFormGroup(){
  return this.formBuilder.group({
    skillName: ['', RxwebValidators.unique()]
  })
}

Compare Validation

The most common scenario of compare validation is password and confirmPassword comparison

Without RxWeb

checkPasswordField custom function

this.myForm = this.fb.group({
  password: ['', [Validators.required]],
  confirmPassword: ['']
}, {validator: this.checkPasswords })

checkPasswords(group: FormGroup) { // here we have the 'passwords' group
  let pass = group.get('password').value;
  let confirmPass = group.get('confirmPass').value;

  return pass === confirmPass ? null : { notSame: true }     
}

With RxWeb

using fieldName property of inbuilt compare validation

Example : open

this.userFormGroup = this.formBuilder.group({
  password:['',], 
  confirmPassword:['', RxwebValidators.compare({fieldName:'password' })], 
});

There are many more inbuilt validations in RxWebValidators categorized into string, datetime, numeric, file and array. To use the RxwebValidators install using the below command :

npm i @rxweb/reactive-form-validators

To know more refer the rxwebio documentation section

Discover and read more posts from Ushmi Dave
get started