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

查看:24
本文介绍了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等验证器都是的内置属性 元素.这就是它们阻止表单提交的原因:它们是浏览器原生的.另一方面,自定义验证器(您自己添加的验证器)由 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.

希望这能帮助其他人.

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

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