如何验证空格/空格?[Angular 2]

Eus*_*ace 32 validation input typescript angular

我想在我的棱角2形式中避免使用空格/空格?可能吗?如何才能做到这一点?

Pra*_*M P 102

您可以创建自定义验证程序来处理此问题.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])
Run Code Online (Sandbox Code Playgroud)

将noWhitespaceValidator方法添加到组件中

public noWhitespaceValidator(control: FormControl) {
    const isWhitespace = (control.value || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true };
}
Run Code Online (Sandbox Code Playgroud)

并在HTML中

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
Run Code Online (Sandbox Code Playgroud)

  • 我认为我更喜欢这种方法,因为它使规则可以重复使用.即使被我的反应标记为正确的. (10认同)
  • 要使其在其他组件中可重用:将'public'替换为'export function',然后将其放入文件(例如:src/app/utils/no-whitespace.validator.rs),并添加该行以导入FormControl.现在您可以将此验证器导入您喜欢的任何控件:) (6认同)
  • //以上答案是完美的,仅建议进行一项检查以避免与 angular 所需的验证器发生冲突。public noWhitespaceValidator(control: FormControl) { const isWhitespace = control.value.length &gt; 0 &amp;&amp; (control.value).trim().length === 0; const isValid = !isWhitespace; 返回有效吗?空:{'空白':真};} (3认同)

Bru*_*oão 13

也许这篇文章可以帮助你http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

在这种方法中,您必须使用FormControl然后监视值更改,然后将掩码应用于值.一个例子应该是:

...
form: FormGroup;
...


ngOnInit(){
    this.form.valueChanges
            .map((value) => {
                // Here you can manipulate your value
                value.firstName = value.firstName.trim();
                return value;
            })
            .filter((value) => this.form.valid)
            .subscribe((value) => {
               console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
            });

}
Run Code Online (Sandbox Code Playgroud)


Cam*_*eva 9

我认为一个简单而干净的解决方案是使用模式验证。

下面的模式将允许一个字符串,它开始以空格,将不允许包含字符串只有空格

/^(\s+\S+\s*)*(?!\s).*$/
Run Code Online (Sandbox Code Playgroud)

可以在为表单组的对应控件添加验证器时设置:

const form = this.formBuilder.group({
            name: ['', [
                Validators.required,
                Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
            ]]
        });
Run Code Online (Sandbox Code Playgroud)

  • `Validators.pattern(/[\S]/)` 更干净、更具可读性,但也需要至少一个字符。 (13认同)

Dil*_*age 8

如果您使用 Angular Reactive Forms,您可以创建一个带有函数的文件 - 验证器。这将不允许只输入空格。

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的组件打字稿文件中使用像这样的验证器。

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});
Run Code Online (Sandbox Code Playgroud)

  • 我知道这个答案已经有一年多了,但我刚刚尝试过。当我创建表单控件时,我将其默认为“”而不是 null,这导致了无限循环。我将默认值更改为 null 并继续测试。如果我进入该字段,输入几个字符然后删除它们,它会说该字段是有效的,即使它应该未通过所需的验证。这是一个耻辱。我真的很喜欢这个解决方案。 (2认同)
  • 我在代码中尝试了这种方法,但即使控件的值为空,它也不会抛出所需的错误。因此在 control.setvalue(''); 下面的函数 {required : true} 中返回 它就像一个魅力。谢谢。 (2认同)

小智 7

另一种方法是使用 Angular 模式验证器并匹配任何非空白字符。

const nonWhitespaceRegExp: RegExp = new RegExp("\\S");

this.formGroup = this.fb.group({
  name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
Run Code Online (Sandbox Code Playgroud)


she*_*ani 6

防止用户在Angular 6的文本框中输入空间

<input type="text" (keydown.space)="$event.preventDefault();" required />
Run Code Online (Sandbox Code Playgroud)

  • @Nicky你可以,但是如果用户想要粘贴一些东西(合法的)怎么办?禁用粘贴会使可用性变得更差。 (9认同)
  • 您仍然可以粘贴空格,或使用Alt + 0160。 (3认同)

Akl*_*ngh 6

    export function noWhitespaceValidator(control: FormControl) {
       const isSpace = (control.value || '').match(/\s/g);
       return isSpace ? {'whitespace': true} : null;
}
Run Code Online (Sandbox Code Playgroud)

使用

 password: ['', [Validators.required, noWhitespaceValidator]]
Run Code Online (Sandbox Code Playgroud)

在模板/html

<span *ngIf="newWpForm.get('password').hasError('whitespace')">
    password cannot contain whitespace
</span>
Run Code Online (Sandbox Code Playgroud)


Dea*_*ers 5

我所做的是创建了一个验证器,该验证器的作用与minLength的angular相同,只是我添加了trim()

import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';


@Injectable()
export class ValidatorHelper {
    ///This is the guts of Angulars minLength, added a trim for the validation
    static minLength(minLength: number): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            if (ValidatorHelper.isPresent(Validators.required(control))) {
                return null;
            }
             const v: string = control.value ? control.value : '';
            return v.trim().length < minLength ?
                { 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
                null;
        };
    }

    static isPresent(obj: any): boolean {
        return obj !== undefined && obj !== null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我在app.component.ts中覆盖了angular提供的minLength函数。

import { Component, OnInit } from '@angular/core';    
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {  
  constructor() { }

  ngOnInit(): void {       
    Validators.minLength = ValidatorHelper.minLength;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,随处都使用了内置在验证器中的angular的minLength,它将使用您在辅助程序中创建的minLength。

Validators.compose([
      Validators.minLength(2)         
    ]);
Run Code Online (Sandbox Code Playgroud)


Vil*_*kas 5

以下指令可以与 Reactive-Forms 一起使用来修剪所有表单字段,以便标准Validators.required工作正常:

@Directive({
  selector: '[formControl], [formControlName]',
})
export class TrimFormFieldsDirective {
  @Input() type: string;

  constructor(@Optional() private formControlDir: FormControlDirective, 
              @Optional() private formControlName: FormControlName) {}

  @HostListener('blur')
  @HostListener('keydown.enter')
  trimValue() {
    const control = this.formControlDir?.control || this.formControlName?.control;
    if (typeof control.value === 'string' && this.type !== 'password') {
      control.setValue(control.value.trim());
    }
  }
}
Run Code Online (Sandbox Code Playgroud)