加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2自定义表单验证不会阻止调用onSubmit

发布时间:2020-12-17 17:39:37 所属栏目:安全 来源:网络整理
导读:也许我是愚蠢但我不能为我的生活弄清楚如何获得自定义表单验证,以便在验证失败时停止onSubmit被调用.在创建新的Control时,我尝试使用 HTML语法(通过将自定义验证关键字直接添加到表单组件的htmlTemplate中)以及代码.我还没有看到任何暗示此功能不适用于自定
也许我是愚蠢但我不能为我的生活弄清楚如何获得自定义表单验证,以便在验证失败时停止onSubmit被调用.在创建新的Control时,我尝试使用 HTML语法(通过将自定义验证关键字直接添加到表单组件的htmlTemplate中)以及代码.我还没有看到任何暗示此功能不适用于自定义验证器的内容.

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

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

And here’s a link to the plunkr

我希望有人可以告诉我如何使其正常工作,或者指向一些文件,承认这不会像我期望的那样工作.

解决方法

事实证明我确实是愚蠢的.诸如required,minLength,maxLength和pattern之类的验证器都是< input>的内置属性.元件.这就是他们阻止表单提交的原因:它们是浏览器的原生.另一方面,自定义验证器(您自己添加的验证器)由Angular管理,但是当单击提交按钮时,它们无法阻止提交表单.

希望这有助于其他人下线.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读