【发布时间】:2016-09-22 00:06:37
【问题描述】:
也许我很笨,但我一辈子都无法弄清楚如何让自定义表单验证在验证失败时停止调用 onSubmit。在创建新控件时,我尝试使用 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
我希望有人可以告诉我如何让它正常工作,或者向我指出一些文档,承认这不能像我预期的那样工作。
【问题讨论】: