我想在我的角度 2 形式中避免空格/空格?可能吗?如何做到这一点?
您可以创建自定义验证器来处理此问题。
new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])
将 noWhitespaceValidator 方法添加到组件
public noWhitespaceValidator(control: FormControl) {
return (control.value || '').trim().length? null : { 'whitespace': true };
}
并在 HTML 中
<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
一个简单而干净的解决方案是使用模式验证。
以下模式将允许以空格开头的字符串,并且不允许仅包含空格的字符串:
/^(s+S+s*)*(?!s).*$/
可以在为表单组的相应控件添加验证器时设置它:
const form = this.formBuilder.group({
name: ['', [
Validators.required,
Validators.pattern(/^(s+S+s*)*(?!s).*$/)
]]
});
也许这篇文章可以帮助你 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));
});
}
防止用户在 Angular 6 的文本框中输入空格
<input type="text" (keydown.space)="$event.preventDefault();" required />
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>
如果您使用的是 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 模式验证器并匹配任何非空格字符。
const nonWhitespaceRegExp: RegExp = new RegExp("\S");
this.formGroup = this.fb.group({
name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
我所做的是创建一个验证器,它对 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)
]);
以下指令可以与响应式表单一起使用来修剪所有表单字段,以便标准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());
}
}
}
这与下面对我有用的答案略有不同:
public static validate(control: FormControl): { whitespace: boolean } {
const valueNoWhiteSpace = control.value.trim();
const isValid = valueNoWhiteSpace === control.value;
return isValid ? null : { whitespace: true };
}
为避免表单提交,只需在输入字段中使用 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;
}
}
要自动删除输入字段中的所有空格,您需要创建自定义验证器。
removeSpaces(c: FormControl) {
if (c && c.value) {
let removedSpaces = c.value.split(' ').join('');
c.value !== removedSpaces && c.setValue(removedSpaces);
}
return null;
}
它适用于输入和粘贴的文本。
我有一个要求,在名字和姓氏中是用户输入,这是必填字段,用户不应该能够点击空格作为第一个字符。
从node_modules导入抽象控件。
import { AbstractControl } from '@angular/forms';
检查第一个字符是否为空格如果是,则清空该值并返回必需:true。如果没有返回空
值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]]
})
要验证输入开头的空格,您只需调用 change 事件并为此执行内联函数即可。
<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/>
如果您在 Angular 2+ 中使用响应式形式,则可以借助 (blur)
删除前导空格和尾随空格
应用.html
<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());
}
}
在你的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)
])
})
经过大量试验,我发现带有空格的字母数字[a-zA-Z\s]*
例:
纽约
新德里
我使用了表单值更改函数来防止空格。 时间它将修剪所有字段之后所需的验证将 适用于空白字符串。
像这里:-
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 });
}
}
}
In 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);
}
示例代码
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()])],
我来晚了,但我发现大多数答案对于我的用例来说并不完全有效。我正在使用正则表达式匹配,它可以正确检测 UTF 8 空格(.trim(( 不会(。此外,我还添加了一个空值检查。代码是打字稿,但应该很容易转换为javascript。
notOnlyWhitespaceValidator(control: AbstractControl) {
const isWhitespace = control.value && control.value.length > 0 && (control.value as string).match(/[^-s]/) === null;
const isValid = !isWhitespace;
return isValid ? null : { 'only-whitespace': true };
}
这是一个测试套件(开玩笑(
describe('notOnlyWhitespaceValidator', () => {
it('should not trigger on missing value', () => {
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(''))).toEqual(null);
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl())).toEqual(null);
});
it('should trigger on only whitespace', () => {
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(' '))).toEqual({ 'only-whitespace': true });
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl('n'))).toEqual({ 'only-whitespace': true });
// check utf 8 zero with space
const utf8Space = 'ufeff';
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(utf8Space))).toEqual({
'only-whitespace': true,
});
});
it('should not trigger on valid input', () => {
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(' Whatever is valid '))).toEqual(null);
expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl('!'))).toEqual(null);
});
});
简单地添加一个模式验证器
Validators.pattern('[\S]{1,}[\S\s]*|[\s]*[\S]{1,}[\S\s]*')
这将检查前导部分或后面部分中的空格。
最好使用 Angular 代码创建自定义验证器并像这样自定义它:
export function required(control: AbstractControl): ValidationErrors | null {
return isEmptyInputValue(control?.value) ? {'required': true} : null;
}
function isEmptyInputValue(value: any): boolean {
return value == null ||
(typeof value === 'string' && value.trim().length === 0) ||
(Array.isArray(value) && value.length === 0);
}
然后,您可以使用自己的required
验证器而不是Angular Validator。