Home > other >  Adding validation in an input field for options selected using Template driven forms in angular 13
Adding validation in an input field for options selected using Template driven forms in angular 13

Time:10-25

I am new to Angular and got stuck in validation.

My problem is that I have dropdown menu with 4 options to select. when user selected one option I want an input field to change validation in such a way that:

If user select option 1 in the drop down than I want in the next input field to have the validation required and maximum length 8 numbers. likewise If the user select option 2 in the drop down. I want the input field to have the validation required and maximum length of 5 number. so i got stuck in validation how to do it. Any help and idea would be greatly appreciated## Heading ##

CodePudding user response:

I suggest you to use ReactiveFormsModule. Add in app.module.ts

@NgModule({
   ...
   imports: [
       ...
       ReactiveFormsModule,
       ...
   ]
   ...
})
export class AppModule { }

in your component yourcomponent.component.ts

maxlenght: number = 10; //default value
insertForm: FormGroup = this.fb.group({
    selectType: ['', Validators.required],
    otherField: [''],
});

constructor(private fb: FormBuilder) {}

change() {
    this.maxlenght =  this.insertForm.get('selectType').value || 10;
    this.insertForm.get('otherField').clearValidators();
    this.insertForm.get('otherField').addValidators(Validators.maxLength(this.maxlenght));
}

isValid() {
    console.log(this.insertForm.valid);
}

in your component yourcomponent.component.html

<div [formGroup]="insertForm">
  <div>
    <select name="select" formControlName="selectType" (change)="change()">
      <option value="11">11</option>
      <option value="12">12</option>
      <option value="13">13</option>
      <option value="14">14</option>
    </select>
  </div>
  <div>
    <input formControlName="otherField" [maxlength]="maxlenght" />
    <small *ngIf="insertForm.get('otherField')?.errors" >
      maxlength exceeded
    </small>
  </div>
  <div>
    <button (click)="isValid()">is valid?</button>
  </div>
</div>

for a complete example: https://stackblitz.com/edit/angular-ivy-1ajwxq?file=src/app/app.component.html

  • Related