简体   繁体   English

如何在angular2中单击按钮时触发表单验证

[英]How to trigger form validation on button click in angular2

I am working on angular2 application in which I have to apply validation on the input fields. 我正在开发angular2应用程序,我必须在输入字段上应用验证。

I have same code here 我这里有相同的代码

http://plnkr.co/edit/6RkM0eRftf3KQpoDCktz?p=preview http://plnkr.co/edit/6RkM0eRftf3KQpoDCktz?p=preview

Its work fine for me but i want to trigger the validation on button click and show the all the validation messages which are invalid 它的工作正常,但我想触发按钮点击验证并显示所有无效的验证消息

currently it activated when i click on fields. 当前我点击字段时激活它。

I have tried this 我试过这个

saveUser() {
        if (this.userForm.valid) {
            alert(`Name: ${this.userForm.value.name} Email: ${this.userForm.value.email}`);
        } else {
            this.userForm.validator();
        }
    }

Its not working as expected. 它没有按预期工作。

How do i trigger those validation on button click, I want button to be active all the time. 如何在按钮点击时触发这些验证,我希望按钮始终处于活动状态。

You could try to leverage a submitted property of the form control when displaying errors. 在显示错误时,您可以尝试利用表单控件的submitted属性。 This could be used in the corresponding ngIf to display these messages. 这可以在相应的ngIf用于显示这些消息。

<span *ngIf="submitted && !this.userForm.controls.email.valid">...</span>

You need to initialize the submitted property to false by default and set it to true when calling the saveUser method: 默认情况下,您需要将submitted属性初始化为false,并在调用saveUser方法时将其设置为true:

@Component({
})
export class SomeComponent {
  constructor() {
    this.submitted = false;
  }

  saveUser() {
    this.submitted = true;
    (...)
  }
}

This way they will be visible only after the form has been submitted. 这样,只有在提交表单后才能看到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM