【问题标题】:Fields should not accept spaces at start and end of input字段不应在输入的开头和结尾处接受空格
【发布时间】:2020-08-10 08:13:53
【问题描述】:

在我的一个表单中,所有输入字段都只允许提交空白字符。对于输入两端的空白字符也是如此。

表单以 HTML 格式设置并具有角度验证器。

我想检查一下:输入的开头或结尾是否有空格,以及输入是否只有空格。

要显示的通用消息:“输入无效” 我制作的模式是:“/^\s|\s$/”

如何在我的 .ts 文件中使用它? 任何直觉都会有所帮助。

【问题讨论】:

标签: javascript html angular


【解决方案1】:

有很多优秀的作品可以完成这项任务。试试这个块,它可能对你有用。

import { AbstractControl, ValidationErrors } from '@angular/forms';
  
export class UsernameValidator {
    static cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
        if((control.value as string).indexOf(' ') >= 0){
            return {cannotContainSpace: true}
        }
  
        return null;
    }
}

此代码 sn-p 来自 'https://www.itsolutionstuff.com/post/angular-form-validation-no-whitespace-allowed-exampleexample.html'

试一试。

【讨论】:

    【解决方案2】:

    为空白创建自定义验证器

        import { AbstractControl, ValidatorFn } from '@angular/forms';
    
    export function whiteSpaceValidator(control: AbstractControl) {
      const space = /^([ ]+)$/;
       const spaceStart = /^([ ]+)/
        const spaceEd = /([ ]+$)/
      if (space.test(control.value) || spaceStart.test(control.value) || spaceEd.test(control.value)) {
        return { whiteSpace: true };
      }
      return null;
    }
    

    在表单上添加此验证器

     this.discountForm = this.formBuilder.group({
          name: ['', [Validators.required, whiteSpaceValidator]]
        });
    

    【讨论】:

    • 我认为代码不符合问题中的要求。
    【解决方案3】:

    为了检查字符串开头和结尾的空格,javascript中有一个String方法可以删除字符串开头和结尾的空格。

    例如: var msg = " helloWorld " //假设这是用户提供的输入,在字符串的开头和结尾都有空格。

    msg = msg.trim() // 此语句将删除字符串开头和结尾的空格并生成输出为“helloworld”

    所以现在在您的自定义验证器函数中,在输入字段上使用 trim 方法。

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2019-11-06
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多