heliya rb
heliya rb

Reputation: 830

How to set multi validation to form control?

I have a simple form with one input. I want to set multi validation in this input. I can set one validation for this like below but I want to set multi validation. please help me this is my Html code:

   <form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
       <div class="input-holder">
          <input type="text" maxlength="11" inputmode="numeric" digitOnly formControlName="phoneNumber" />
          <input type="submit" value="دریافت لینک دانلود" [disabled]="!contactForm.valid">
       </div>
   </form>

and this is the ts file:

contactForm: FormGroup;

  constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", [Validators.required])
    });
  }
 onSubmit() {
    console.log(this.contactForm.value);
  }

I want to set

Validators.minLength(11)

and

Validators.maxLength(11)

and ...

Upvotes: 0

Views: 4403

Answers (2)

Gaurang Dhorda
Gaurang Dhorda

Reputation: 3387

Complete Working Example You can find out in this StackBlitz Link,

Thought, Answer is already accepted and have working solution I have to give one of the robust solution for applying custom-validation multiple times.. At first it feels very long but at Long-Run of application scaling and re-usability You can re-use Your Own Custom-Validator-Function multiple time.

For Example, If you have pass-word field and you want to make that pass-word field to make validation like PassWord must have below validations...

  • Required
  • At least one SMALL letter is allowed
  • At least one UPPER letter is allowed
  • At least one NUMERIC letter is allowed
  • At least one SPECIAL-CHARACTER is allowed
  • At least Eight Letter is allowed

So Doing this type of Multiple validation in angular we are going to use one custom-Validation-Function-directive for better angular support. Create new file custom-validator.directive and then in this file put this code...

import{AbstractControl, ValidatorFn} from '@angular/forms';

export function customValidation(): ValidatorFn{
      return (control: AbstractControl) : {[key:string]: boolean} | null =>{
             const errorObject = {};

             const SMALL_LETTER_REGEXP = /^(?=.*[a-z])/;
             const UPPER_LETTER_REGEXP = /^(?=.*[A-Z])/;
             const NUMERIC_REGEXP = /^(?=.*[0-9])/;
             const SPECIAL_CHAR_REGEXP = /^(?=.*\W)/;
             const AT_LEAST_EIGHT_REGEXP = /^(?=.{8,})/

             if (SMALL_LETTER_REGEXP.test(control.value)){
             }else {
                 errorObject['atLeastOneSmallLetter'] = true;
              }
             if (UPPER_LETTER_REGEXP.test(control.value)){
             }else {
                errorObject['atLeastOneUpperLetter'] = true;
              }
            if(NUMERIC_REGEXP.test(control.value)){
            }else {
                errorObject['atLeastOneNumeric'] = true;
            }
            if(SPECIAL_CHAR_REGEXP.test(control.value)){
            }else {
                errorObject['atLeastOneSpecialChar'] = true;
            }
            if(AT_LEAST_EIGHT_REGEXP.test(control.value)){
            }else {
                errorObject['atLeastOneEightLength'] = true;
            }
         return errorObject;
      };
}

Now import this file in your component.ts where your formsGroup and FormsBuilder is there...

import {customValidation} from './custom-validator.directive';

export class AppComponent  {
    formGroup: FormGroup;
    constructor(private fb: FormBuilder){}
    ngOnInit(){
        this.formGroup = this.fb.group({
                             password: ['', [ Validators.required,  customValidation()]]
            })
    }
    get password(){
        return this.formGroup.get('password');
    }
}

In, Above code in this line password: ['', [ Validators.required, customValidation()]], we are passing customValidation() function into the formGroup. this way we are applying all validations in this password form-control.

So each and every input key-field changes we are checking all password rules validation asynchronously. And tell user to enter only valid password matching character strings...

Your Template.HTML is

<form [formGroup]="formGroup">
     <div  class="form-group col-md-6">
         <label for="password">Enter Pass-Word</label>
         <input id="password" class="form-control" placeholder="Password" type="password" formControlName="password" >

     </div>

     <div class="col-md-6 " *ngIf="password.invalid && (password.dirty || password.touched)">
         <div class="alert alert-danger " *ngIf="password.hasError('required')">
            <ul> <li> Required  </li> </ul>
         </div>
         <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneSmallLetter')">
            <ul> <li> At least one SMALL letter is allowed  </li> </ul> 
         </div>
         <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneUpperLetter')">
            <ul> <li> At least one UPPER letter is allowed  </li> </ul>
         </div>
         <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneNumeric')">
            <ul> <li> At least one NUMERIC letter is allowed  </li> </ul>
         </div>
         <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneSpecialChar')">
            <ul> <li> At least one SPECIAL-CHARACTER is allowed  </li> </ul>
         </div>
         <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneEightLength')">
            <ul> <li> At least Eight Letter is allowed  </li> </ul>
         </div>
     </div>
</form>

Upvotes: 2

Chellappan வ
Chellappan வ

Reputation: 27303

Since FormControl validatorOrOpts is array you can set multiple Validation like this

constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", [Validators.required, Validators.minLength(11)])
    });
  }

or use Validators.compose

Compose multiple validators into a single function that returns the union of the individual error maps for the provided control

 constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", Validators.compose([Validators.required, Validators.minLength(11)]))
    });
  }

Upvotes: 4

Related Questions