[英]how can I prevent user from entering space in a password field in angular?
我想防止在密碼字段中輸入任何空格。 我認為我的代碼是正確的,但也許有些東西已經更新,但我不知道我該怎么做。
這是我的代碼。首先我把 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;
}
}
}
您可以使用模式驗證器: https://angular.io/api/forms/Validators 。
你好.component.ts
import { Component, Input } from "@angular/core";
import { FormControl, FormGroup, Validators } from "@angular/forms";
@Component({
selector: "hello",
template: `
<form [formGroup]="form">
<div class="form-group">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input
type="text"
formControlName="password"
class="form-control"
id="exampleInputPassword1"
/>
<div
*ngIf="
form.controls['password'].invalid &&
(form.controls['password'].dirty ||
form.controls['password'].touched)
"
class="alert alert-danger"
>
<div *ngIf="password?.errors?.pattern">No space permitted</div>
</div>
</div>
</form>
`,
styles: [
`
h1 {
font-family: Lato;
}
`
]
})
export class HelloComponent {
form = new FormGroup({
email: new FormControl("", [Validators.required]),
password: new FormControl("",
[Validators.pattern(/^\S*$/)] // <-- pattern with the regular expression which detects spaces
)
});
get email() {
return this.form.get("email");
}
get password() {
return this.form.get("password");
}
}
這里是stackblitz上的代碼: https://stackblitz.com/edit/angular-ivy-gylfmt?file=src/app/hello.component.ts
只需將onkeypress="return event.charCode != 32"
添加到您的輸入字段中,例如
<input onkeypress="return event.charCode != 32">
32 是空格的 ASCII 碼。 因此,您允許除空格以外的所有字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.