【问题标题】:Show Validation Message on submit in Angular 4 Reactive Forms在 Angular 4 响应式表单中提交时显示验证消息
【发布时间】:2017-11-30 03:33:07
【问题描述】:

我正在使用 Angular 4,反应式表单。我想在用户单击提交/创建帐户按钮时显示验证错误消息。 这是我正在使用的 HTML 和打字稿代码。

<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">

  <div class="form-group">
    <input type="text" 
           id="firstname" 
           name="firstname" 
           formControlName="firstname" 
           placeholder="First Name">
    <span *ngIf="!signupForm.get('firstname').valid && signupForm.get('firstname').touched" 
           class="help-block"> Please Enter First Name (Minimum 2 Characters)</span>
  </div>

  <div class="form-group">
    <input type="text" 
           id="lastname" 
           name="lastname" 
           formControlName="lastname" 
           placeholder="Last Name">
    <span *ngIf="!signupForm.get('lastname').valid && signupForm.get('lastname').touched" 
           class="help-block"> Please Enter Last Name (Minimum 2 Characters)</span>
  </div>

  <div class="form-group">
    <button type="submit" 
            class="btn btn-success btn-lg btn-qte">Create Account</button>
  </div>

</form>

键入脚本代码


export class UserRegistrationComponent implements OnInit {
    signupForm: FormGroup;

    ngOnInit() {
        this.signupForm = new FormGroup({
            'firstname': new FormControl(null, [Validators.required, Validators.minLength(2)]),
            'lastname': new FormControl(null, [Validators.required, Validators.minLength(2),]),
            'businessname': new FormControl(null),
            'phonenumber': new FormControl(null, [Validators.required]),
            'email': new FormControl(null, [Validators.required, Validators.email]),
            'password': new FormControl(null, [Validators.required]),
            'confirmpassword': new FormControl(null, Validators.required)

        });
    }

    onSubmit() {
        console.log(this.signupForm)
    }

}

【问题讨论】:

    标签: angular forms typescript angular-reactive-forms


    【解决方案1】:

    您可以使用 from markAllAsTouched() 方法执行此操作。 它会将所有表单控件标记为已触摸,并在需要时触发验证错误

    onSubmit() {
        this.signupForm.markAllAsTouched();
    }
    

    【讨论】:

      【解决方案2】:

      要通过formGroup获取表单控件的toucheddirtyvalid等属性,请使用:

      signupForm.controls.firstname.touched。同样的方式你可以得到其他属性,如有效和无效。

      如果您创建了 FormControl 的单个对象,那么您可以在不使用 formGroup 的情况下以 firstname.touched 访问该对象属性。

      有关模型驱动表单中验证的更多信息,请参阅Model Driven Form Validations 此处。

      【讨论】:

        【解决方案3】:

        类似

        onSubmit() {
            console.log(this.signupForm)
            this.signupForm.controls['firstname'].markAsTouched()
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-12
          • 2020-07-27
          • 2015-08-04
          • 2017-11-08
          • 1970-01-01
          • 2019-02-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多