【问题标题】:Angular dropdown validation角度下拉验证
【发布时间】:2018-09-15 15:13:37
【问题描述】:

我正在使用带有表单验证器的 Angular 5。我正在尝试验证选择下拉列表,以避免在用户从选择中选择项目的情况下发送表单。问题是验证不起作用。验证器适用于输入控件但不适用于下拉菜单。

<div class="form-control">
    <label class="form-control__label" for="accionReglas">País *</label>
    <p-dropdown formControlName="paisDropdown" class="dropdown" [options]="countriesOptions" [readonly]="this.isReadOnly || filtersForm.get('nacInterRadioButton').value === 'N'" filter="true" placeholder="Seleccione su país"  required="true"></p-dropdown>
    <div *ngIf="filtersForm.get('paisDropdown').errors && (filtersForm.get('paisDropdown').dirty || filtersForm.get('paisDropdown').touched)">
        <span *ngIf="filtersForm.get('paisDropdown').errors.required" class="form-control__msg-txt">El país es obligatorio.</span>
    </div>
</div>

TypeScript 代码:

import { FormBuilder, FormGroup, FormControl, Validators, Validator } from '@angular/forms';

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

非常感谢!!!

【问题讨论】:

    标签: html angular


    【解决方案1】:

    在提交表单上,您必须为每个控制器设置 markAsTouched。

    实时示例:https://stackblitz.com/edit/angular-obcju1

    HTML:

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

    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
      }
    
    }
    

    【讨论】:

    • 在 Angular 8 中有一个新的方法调用 .markAllAsTouched()。在这个例子中,我们只需要删除 subpit 中的 for 循环并使用 this.filtersForm.markAllAsTouched()
    【解决方案2】:

    HTML:-

    <input class="form-control"  type="text" formControlName="price" />
    
    <div  class="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)]
    
    });
    

    当下拉值更改时,为价格字段添加验证。

    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();
      }
     });
    

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多