【发布时间】:2017-01-07 07:11:07
【问题描述】:
我想在我的 angular 2 表单中避免空格/空格? 可能吗? 如何做到这一点?
【问题讨论】:
-
您只需将字段修剪为双向数据绑定。您也可以考虑自定义管道
-
或许这篇文章能帮到你blog.angular-university.io/…
标签: angular validation typescript input
我想在我的 angular 2 表单中避免空格/空格? 可能吗? 如何做到这一点?
【问题讨论】:
标签: angular validation typescript input
为避免表单提交,只需在输入字段中使用required attr。
<input type="text" required>
或者,提交后
提交表单后,您可以使用 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;
}
}
【讨论】:
也许这篇文章可以帮到你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));
});
}
【讨论】:
您可以创建自定义验证器来处理此问题。
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>
【讨论】:
noWhitespaceValidator 以允许在tsconfig.json 中设置strictNullChecks: true?
我所做的是创建了一个验证器,它对 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;
}
}
然后我在我的 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;
}
}
现在在任何使用 angular 内置验证器的 minLength 的地方,它都会使用您在帮助程序中创建的 minLength。
Validators.compose([
Validators.minLength(2)
]);
【讨论】:
如果您使用 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;
}
然后在你的组件打字稿文件中使用像这样的验证器。
this.formGroup = this.fb.group({
name: [null, [Validators.required, removeSpaces]]
});
【讨论】:
防止用户在 Angular 6 的文本框中输入空格
<input type="text" (keydown.space)="$event.preventDefault();" required />
【讨论】:
这与下面对我有用的答案略有不同:
public static validate(control: FormControl): { whitespace: boolean } {
const valueNoWhiteSpace = control.value.trim();
const isValid = valueNoWhiteSpace === control.value;
return isValid ? null : { whitespace: true };
}
【讨论】:
要从输入字段中自动删除所有空格,您需要创建自定义验证器。
removeSpaces(c: FormControl) {
if (c && c.value) {
let removedSpaces = c.value.split(' ').join('');
c.value !== removedSpaces && c.setValue(removedSpaces);
}
return null;
}
它适用于输入和粘贴的文本。
【讨论】:
.trim 删除字符串开头和结尾的空格,而 split/join 删除所有空格(并且只有空格,而不是所有空格,例如制表符、换行符)字符串。
经过大量试验,我发现 [a-zA-Z\\s]* 表示带有空格的字母数字
例子:
纽约
新德里
【讨论】:
我使用了表单 valueChanges 函数来防止空格。每一个 在所需的验证之后它将修剪所有字段的时间 适用于空白字符串。
喜欢这里:-
this.anyForm.valueChanges.subscribe(data => {
for (var key in data) {
if (data[key].trim() == "") {
this.f[key].setValue("", { emitEvent: false });
}
}
}
已编辑 --
如果您在表单控件中使用任何数字/整数,在这种情况下,修剪功能将无法直接工作 像这样使用:
this.anyForm.valueChanges.subscribe(data => {
for (var key in data) {
if (data[key] && data[key].toString().trim() == "") {
this.f[key].setValue("", { emitEvent: false });
}
}
}
【讨论】:
另一种方法是使用 Angular 模式验证器并匹配任何非空白字符。
const nonWhitespaceRegExp: RegExp = new RegExp("\\S");
this.formGroup = this.fb.group({
name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
【讨论】:
我有一个要求,其中 Firstname 和 Lastname 是用户输入,它们是必填字段,并且用户不应将空格作为第一个字符。
从 node_modules 导入 AbstractControl。
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;
}
}
如果第一个字符是空格,上面的代码会触发错误,并且不允许空格作为第一个字符。
并在表单构建器组中声明
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>
在 hello.component.ts 中
import { ValidatorFn, FormControl } from '@angular/forms';
const trimValidator: ValidatorFn = (text: FormControl) => {
if (text.value.startsWith(' ')) {
return {
'trimError': { value: 'text has leading whitespace' }
};
}
if (text.value.endsWith(' ')) {
return {
'trimError': { value: 'text has trailing whitespace' }
};
}
return null;
};`
export class AppComponent {
control = new FormControl('', trimValidator);
}
【讨论】:
在你的 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>
在您的 app.componen.ts 文件中
import { Validators, FormGroup, FormControl } from "@angular/forms";
signupForm: FormGroup;
ngOnInit(){
this.signupForm = new FormGroup({
name: new FormControl("", [
Validators.required,
Validators.pattern("^[a-zA-Z]+$"),
Validators.minLength(3)
])
})
【讨论】:
export function noWhitespaceValidator(control: FormControl) {
const isSpace = (control.value || '').match(/\s/g);
return isSpace ? {'whitespace': true} : null;
}
使用
password: ['', [Validators.required, noWhitespaceValidator]]
在模板/html中
<span *ngIf="newWpForm.get('password').hasError('whitespace')">
password cannot contain whitespace
</span>
【讨论】:
以下指令可以与 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());
}
}
}
【讨论】:
要在输入开始时验证空白,您只需调用更改事件并为此执行内联函数。
<input type="text" class="form-control"
placeholder="First Name without white space in starting"
name="firstName"
#firstName="ngModel"
[(ngModel)]="user.FirstName"
(change) ="user.FirstName = user.FirstName.trim()"
required/>
【讨论】:
我认为一个简单而干净的解决方案是使用模式验证。
以下模式允许字符串以空格开头,不允许字符串只包含空格:
/^(\s+\S+\s*)*(?!\s).*$/
可以在为表单组的相应控件添加验证器时设置:
const form = this.formBuilder.group({
name: ['', [
Validators.required,
Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
]]
});
【讨论】:
Validators.pattern(/[\S]/) 更简洁易读,但也需要至少一个字符。
如果您在 Angular 2+ 中使用响应式表单,您可以在 (blur) 的帮助下删除前导和尾随空格
app.html
<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />
app.ts
public trimLeadingAndTrailingSpaces(formControl: AbstractControl) {
if (formControl && formControl.value && typeof formControl.value === 'string') {
formControl.setValue(formControl.value.trim());
}
}
【讨论】:
export function NoWhitespaceValidator(): ValidatorFn {
return (control: AbstractControl): any => {
window.setTimeout(() => {
if (control.value && control.value != '') {
let trimedvalue = control.value.replace(/\s/g, '');
control.setValue(trimedvalue);
}
}, 10);
};
}
username: ['', Validators.compose([Validators.required, NoWhitespaceValidator()])],
【讨论】: