Angular 2自定义表单验证不会阻止onSubmit的调用 [英] Angular 2 custom form Validation does not prevent onSubmit from being called

查看:81
本文介绍了Angular 2自定义表单验证不会阻止onSubmit的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我很傻,但是我终生无法弄清楚如何获取自定义表单验证,以在验证失败时停止onSubmit的调用.创建新的控件时,我尝试使用HTML语法(通过将自定义验证关键字直接添加到表单组件的htmlTemplate中)以及通过代码使用.我还没有看到任何暗示该功能不适用于自定义验证程序的信息.

Perhaps I am being dumb but I cannot for the life of me figure out how to get custom form validation to stop onSubmit from being called when the validation fails. I've tried using both the HTML syntax (by adding the custom validation keyword directly into the htmlTemplate of the form component) as well as through the code, when creating a new Control. I also haven't seen anything that suggests this feature shouldn't work for custom validators.

这是我正在使用的代码的示例

Here's an example of the code I'm using

import { Component, Output, EventEmitter, OnInit } from 'angular2/core';
import { FORM_DIRECTIVES, FormBuilder, Control, ControlGroup} from 'angular2/common';

@Component({
  selector: 'formality-form',
  templateUrl: 'html/formality.html',
  styleUrls: ['styles.css']
})
export class FormalForm implements OnInit {
  formGroup: ControlGroup;

  // Here I register the custom validator to the Control group
  constructor(fb: FormBuilder) {
    this.formGroup = fb.group({
      'date': ['']
    } {validator: FormalForm.customVal});
  }

  // This is my custom validator
  public static customVal(control: ControlGroup){
    return {isFail:true};
  }

  // I would like for this to never be called, since the custom validator is in
  // a state of perpetual fail.
  onSubmit(): void {
    console.log(this.formGroup.value);
    alert('onSubmit called; formGroup.valid = ' + this.formGroup.valid);
  }
}

这是指向plunkr的链接

我希望有人可以向我展示如何使其正常工作,或者向我介绍一些文档,该文档确认该文档不符合我的预期.

I'm hoping someone can either show me how to get this working correctly, or point me towards some documentation that acknowledges this doesn't work as I'm expecting.

推荐答案

原来我确实很傻.诸如requiredminLengthmaxLengthpattern之类的验证器都是<input>元素的内置属性.这就是为什么它们阻止表单提交的原因:它们是浏览器的本机.另一方面,自定义验证器(您自己添加的验证器)由Angular管理,但它们无法停止表单单击提交按钮后,将不会被提交.

Turns out I am indeed dumb. Validators such as required, minLength, maxLength, and pattern are all built-in attributes of the <input> element. This is why they prevent form submission: they're native to the browser. On the otherhand, custom validators (ones that you add yourself) are managed by Angular, but they cannot stop a form from being submitted when the submit button is clicked.

希望这可以帮助其他人.

Hope this helps someone else down the line.

这篇关于Angular 2自定义表单验证不会阻止onSubmit的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆