Angular dropdown validation

后端 未结 2 1670
走了就别回头了
走了就别回头了 2021-01-15 02:03

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 t

2条回答
  •  借酒劲吻你
    2021-01-15 02:15

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

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

    HTML:

    Enter Input ... maxlength Error ....
    Enter Country ...

    TS:

    export class AppComponent  {
    
      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 in this.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
      }
    
    }
    

提交回复
热议问题