【发布时间】:2021-03-03 22:21:42
【问题描述】:
我想防止在密码字段中输入任何空格。
我认为我的代码是正确的,但可能已经更新了某些内容,但我不知道该怎么办。
这是我的代码。首先我把 login.component.html 然后 login.component.ts 然后验证器文件。
<form [formGroup]="from">
<div class="form-group">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="text"
formControlName="password"
class="form-control"
id="exampleInputPassword1">
<div *ngIf="from.controls['password'].invalid && (from.controls['password'].dirty || from.controls['password'].touched)" class="alert alert-danger">
<div *ngIf="password.errors.noSpaceAllowed">No space permitted</div>
</div>
</div>
</form>
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { TextValidator } from '../validator.validation';
@Component({
selector: 'login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent{
from = new FormGroup({
email : new FormControl('',[Validators.required]),
password : new FormControl('',[TextValidator.noSpaceAllowed]),
});
get email(){
return this.from.get('email');
}
get password(){
return this.from.get('password');
}
}
import { AbstractControl, ValidationErrors } from "@angular/forms";
export class TextValidator{
static noSpaceAllowed(control:AbstractControl) : ValidationErrors | null{
// != -1 means in contains space
if((control.value as string).indexOf('') != -1){
//fire validator
return {noSpaceAllowed : true};
}
else{
return null;
}
}
}
【问题讨论】:
-
尝试使用正则表达式,这里可以找到stackoverflow.com/questions/16334765/…
-
不知道怎么用
标签: angular typescript frontend