【发布时间】:2020-09-19 14:09:22
【问题描述】:
从这里:https://stackoverflow.com/a/42999816/462608
这是我尝试过的:
whitespace-validator.directive.ts
import { Directive } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms';
@Directive({
selector: '[appWhitespaceValidator]'
})
export class WhitespaceValidatorDirective
{
constructor() {}
static appWhitespaceValidator( control: FormControl ): ValidationErrors
{
const isWhitespace = (control.value || '').trim().length === 0;
const isValid = !isWhitespace;
return isValid ? null : { 'whitespace': true };
}
}
在 xyz.ts
import { WhitespaceValidatorDirective } from '../whitespace-validator.directive'
...
this.objFormGroup = this.objFormBuilder.group(
{
blogTitle: [ this.blogs[this.mBlogId].title, [Validators.required, Validators.minLength(5) ] ],
body: [ this.blogs[this.mBlogId].body ],
category: [ this.blogs[this.mBlogId].category ]
} )
get getBlogTitle()
{
return this.objFormGroup.get('blogTitle') as FormControl;
}
在 xyz.html
<div *ngIf = "getBlogTitle.errors?.appWhitespaceValidator">
No spaces are allowed.
</div>
请说明使用此验证器指令的正确方法。这里没有错误,但表单仍然没有抱怨 w.r.t 空格。
在 HTML 中以“反应式”形式使用自定义验证器的方法是什么?
【问题讨论】:
标签: html angular typescript