Angular 中没有空间验证器

The*_*t94 1 regex angular2-forms angular-validation angular angular4-forms

我在我的项目中处理了 10 多个带有许多输入字段的表单。问题是我的字段将空格作为值。至于现在我所做的是在更改时获取字段的值并修剪它并用 0 检查长度。如果是,则抛出“不使用空格”,否则取值。

<input (change)='check($event)'>

check(data){
   if(data.trim() === 0 ){
       console.log('contains empty spaces'   
   }else{
        console.log('contains data') 
   }
}
Run Code Online (Sandbox Code Playgroud)

但是随着字段或表单的增加,这将是一个令人头疼的问题。所以我试图把它作为通用模块。所以我会像服务一样使用它。

注意:验证应该发生在借口上(即)'HelloWorld' 应该抛出错误但'Hello World' 不应该。谁能给我一些想法或建议来解决这个问题..

提前致谢

Tom*_*ula 7

trim.validator.ts

export const trimValidator: ValidatorFn = (control: FormControl) => {
  if (control.value.startsWith(' ')) {
    return {
      'trimError': { value: 'control has leading whitespace' }
    };
  }
  if (control.value.endsWith(' ')) {
    return {
      'trimError': { value: 'control has trailing whitespace' }
    };
  }
  return null;
};
Run Code Online (Sandbox Code Playgroud)

在任何想要使用 trim.validator.ts 的组件中

import { trimValidator } from 'path/to/trim.validator'.ts

ctrl: FormControl;

ngOnInit() {
  this.ctrl = new FormControl('', trimValidator);
)
Run Code Online (Sandbox Code Playgroud)

如果您使用模板驱动的表单,则需要创建验证指令。只需按照官方文档中的步骤操作即可

现场演示