Skip to content Skip to sidebar Skip to footer

Angular Dropdown Validation

I'm using Angular 5 with forms validator. I'm trying to validate a select dropdown to avoid send the form without the user select an item from the select. The problem is the valida

Solution 1:

on submit form you have to set markAsTouched for each controller.

live example: https://stackblitz.com/edit/angular-obcju1

HTML:

<form [formGroup]="filtersForm" (ngSubmit)="onSubmit()"><inputtype="text"formControlName="cifInput"/><span *ngIf="hasInputErrorRequired">Enter Input ...</span><span *ngIf="hasInputErrorMaxlength">maxlength Error ....</span><hr><labelfor="accionReglas">País *</label><p-dropdownformControlName="paisDropdown"
      [options]="countriesOptions"placeholder="Seleccione su país"></p-dropdown><span *ngIf="hasDropDownError">Enter Country ...</span><hr><buttontype="submit">submit</button></form>

TS:

export classAppComponent{

  filtersForm: FormGroup;

  countriesOptions = [
      {label: 'New York', value: 'NY'},
      {label: 'Rome', value: 'RM'},
      {label: 'London', value: 'LDN'},
      {label: 'Istanbul', value: 'IST'},
      {label: 'Paris', value: 'PRS'}
  ];

  constructor(private fBuilder: FormBuilder) {

    this.filtersForm = this.fBuilder.group({
      "cifInput": new FormControl("", [ Validators.required, Validators.maxLength(10) ]),
      "paisDropdown": new FormControl("", [ Validators.required ])
    });
  }

  onSubmit() {
    for (let controller inthis.filtersForm.controls) {
      this.filtersForm.get(controller).markAsTouched();
    }

    if(this.filtersForm.valid) {
      console.log('Ok')
    } else {
      console.log('No')
    }
  }

  get hasDropDownError() {
    return (
      this.filtersForm.get('paisDropdown').touched &&
      this.filtersForm.get('paisDropdown').errors &&
      this.filtersForm.get('paisDropdown').errors.required
    )
  }

  get hasInputErrorRequired() {
    const controller = this.filtersForm.get('cifInput');
    return controller.touched && controller.errors && controller.errors.required
  }

  get hasInputErrorMaxlength() {
    const controller = this.filtersForm.get('cifInput');
    return controller.touched && controller.errors && controller.errors.maxlength
  }

}

Solution 2:

Html:-

<input class="form-control"type="text" formControlName="price" />

<divclass="alert alert-danger"
   *ngIf="createForm.controls.price.hasError('required') && 
   createForm.controls.price.touched || 
  createForm.controls.price.dirty)">

    Price Required
                   
 </div>

Ts :-

this.createForm = this.formBuilder.group({ 
   'price':['', [Validators.maxLength(100)],
   'FruitType':['', [Validators.maxLength(100)]

});

when dropdown values changes adding validation for price field.

this.createForm.controls['FruitType'].valueChanges.subscribe(value => {
  if(value !== '') {
    this.createForm.get('price').setValidators([Validators.required]);
    this.createForm.controls['price'].updateValueAndValidity();
  } else {
    this.createForm.get('price').clearValidators();
    this.createForm.controls['price'].updateValueAndValidity();
  }
 });

Post a Comment for "Angular Dropdown Validation"