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)
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)
我认为一个简单而干净的解决方案是使用模式验证。
下面的模式将允许一个字符串,它开始以空格,将不允许包含字符串只有空格:
/^(\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)
如果您使用 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)
小智 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)
防止用户在Angular 6的文本框中输入空间
<input type="text" (keydown.space)="$event.preventDefault();" required />
Run Code Online (Sandbox Code Playgroud)
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)
我所做的是创建了一个验证器,该验证器的作用与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)
以下指令可以与 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)
| 归档时间: |
|
| 查看次数: |
61368 次 |
| 最近记录: |