Angular 如何验证空白/空白?[附件二]

Angular 如何验证空白/空白?[附件二],angular,validation,typescript,input,Angular,Validation,Typescript,Input,我想在我的angular 2表单中避免空白/空白? 可能吗? 如何做到这一点?为了避免表单提交,只需在输入字段中使用requiredattr即可 或者,提交后 提交表单时,可以使用str.trim()删除字符串开头和结尾的空格。我做了一个提交功能,向您展示: submitFunction(formData){ if(!formData.foo){ // launch an alert to say the user the field cannot be empty

我想在我的angular 2表单中避免空白/空白? 可能吗?
如何做到这一点?

为了避免表单提交,只需在输入字段中使用
required
attr即可

或者,提交后

提交表单时,可以使用str.trim()删除字符串开头和结尾的空格。我做了一个提交功能,向您展示:

submitFunction(formData){

    if(!formData.foo){
        // launch an alert to say the user the field cannot be empty
        return false;
    }
    else
    {
        formData.foo = formData.foo.trim(); // removes white 
        // do your logic here
        return true;
    }

}

也许这篇文章可以帮助你

在这种方法中,您必须使用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));
            });

}

您可以创建一个自定义验证器来处理此问题

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])
将noWhitespaceValidator方法添加到组件中

public noWhitespaceValidator(control: FormControl) {
    const isWhitespace = (control.value || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true };
}
在HTML中

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
请输入有效数据

我所做的是创建了一个验证器,除了添加了trim()之外,它对minLength执行与angular相同的操作

现在,只要使用angular的minLength内置验证器,它就会使用您在助手中创建的minLength

Validators.compose([
      Validators.minLength(2)         
    ]);

如果您使用的是角度反应式表单,那么您可以使用一个函数(验证器)创建一个文件。这将不允许只输入空格

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}
然后在您的组件类型脚本文件中使用如下验证程序

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

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

<input type="text" (keydown.space)="$event.preventDefault();" required />

这是一个与下面对我有用的答案略有不同的答案:

publicstaticvalidate(控件:FormControl):{whitespace:boolean}{
const valueNoWhiteSpace=control.value.trim();
const isValid=valueNoWhiteSpace==control.value;
返回值是否有效?null:{whitespace:true};

}
要自动删除输入字段中的所有空格,需要创建自定义验证器

removeSpaces(c: FormControl) {
  if (c && c.value) {
    let removedSpaces = c.value.split(' ').join('');
    c.value !== removedSpaces && c.setValue(removedSpaces);
  }
  return null;
}

它适用于输入和粘贴的文本。

经过大量试验,我发现
[a-zA-Z\\s]*
适用于带空格的字母数字

例如:

纽约

新德里

我使用了form valueChanges函数来防止空白。每一个 它将在需要的验证之后修剪所有字段 为空白字符串工作

就像这里:-

this.anyForm.valueChanges.subscribe(data => {
   for (var key in data) {
        if (data[key].trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }
    }
已编辑--

如果您使用表单控件中的任何数字/整数,在这种情况下,trim函数将无法直接工作 使用类似于:

this.anyForm.valueChanges.subscribe(data => {
  for (var key in data) {
        if (data[key] && data[key].toString().trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }  
  }

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

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

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

我有一个要求,其中Firstname和Lastname是用户输入,这是必填字段,用户不能将空格作为第一个字符

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

this.formGroup = this.fb.group({
  name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
从节点_模块导入抽象控件

import { AbstractControl } from '@angular/forms';
检查第一个字符是否为空格 如果是,则将值留空并返回所需值:true。 如果没有,则返回null

export function spaceValidator(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
    console.log(control.value);
    return { required: true }
}
else {
    return null;
}
}
如果第一个字符是空格,则上述代码将触发错误,并且不允许空格作为第一个字符

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

this.formGroup = this.fb.group({
  name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
并在表单生成器组中声明

this.paInfoForm = this.formBuilder.group({
        paFirstName: ['', [Validators.required, spaceValidator]],
        paLastName: ['', [Validators.required, spaceValidator]]
})

在hello.component.html中

<input [formControl]="name" />
<div *ngIf="name.hasError('trimError')" > {{ name.errors.trimError.value }} </div>
<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />

在app.component.html中

<form [formGroup]="signupForm">

           <input  type="text" name="name" [formControl]="signupForm.controls['name']"
              placeholder="First Name"
              required
            />
     <small
            *ngIf="signupForm.controls['name'].hasError('pattern')"
            class="form-error-msg"
            >First Name without space</small>

    </form>
使用

 password: ['', [Validators.required, noWhitespaceValidator]]
在模板/html中

<span *ngIf="newWpForm.get('password').hasError('whitespace')">
    password cannot contain whitespace
</span>

密码不能包含空格

以下指令可与反应式表单一起使用,以修剪所有表单字段,从而使标准
验证器正常工作。所需的
工作正常:

@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());
    }
  }
}

要验证输入中开始的空白,只需调用change事件并为此执行内联函数


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

以下模式将允许以空格开头的字符串不允许仅包含空格的字符串

/^(\s+\S+\s*)*(?!\s).*$/
可以在为表单组的相应控件添加验证程序时设置:

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

如果在Angular 2+中使用被动形式,可以借助
(blur)

app.html

<input [formControl]="name" />
<div *ngIf="name.hasError('trimError')" > {{ name.errors.trimError.value }} </div>
<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />

谢谢您的帮助,但我需要的是避免用户只添加空格并保存表单。我相信有可能以某种方式验证它。你觉得怎么样?我还没有用angular 2表单的输入掩码。如果我愿意,我会帮助你。但现在我不能。尝试搜索angular 2的屏蔽输入;)非常感谢。我会尽力找到它。你只需将字段修剪为双向数据绑定。您可以考虑自定义管道,这篇文章可以帮助您,我想我更喜欢这种方法,因为它使规则可重用。即使我的响应被标记为正确的响应。为了使其在其他组件中可重用:将“public”替换为“export function”,然后将其放入一个文件(例如:src/app/utils/no whitespace.validator.rs),并将该行添加到import FormControl。现在您可以将此验证器导入任何您喜欢的控件:)@rmcsharry您完全正确。。这就是我们需要编写和维护代码的方式。如何修改
noWhitespaceValidator
以允许在
tsconfig.json
中设置
strictNullChecks:true
?//上述答案非常完美,仅建议进行一次检查以避免与所需的验证器发生冲突。public-noWhitespaceValidator(control:FormControl){const-isWhitespace=control.value.length>0&&(control.value.trim().length==0;const-isValid=!isWhitespace;return-isValid?null:{'whitespace':true};}您仍然可以粘贴空格,或者使用Alt+0160。对于注意到粘贴仍然有效的任何人,可以使用自定义指令禁用粘贴。可以查看@Nicky,但如果用户想要粘贴某些内容(合法),该怎么办?禁用粘贴会使可用性变差。@DanielShatz您可以为此调用change event内联函数。比如输入元素中的(change)=“yourvalue=yourvalue.trim()”。我知道这个答案已经有一年多的历史了,但我只是尝试了一下。当我创建表单控件时,我将其默认为“”而不是null,这导致了一个无限循环。我查
<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />
public trimLeadingAndTrailingSpaces(formControl: AbstractControl) {
    if (formControl && formControl.value && typeof formControl.value === 'string') {
        formControl.setValue(formControl.value.trim());
    }
}