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;
}
}
}
解决方案
只需添加onkeypress="return event.charCode != 32"
到您的输入字段中
<input onkeypress="return event.charCode != 32">
32 是空格的 ASCII 码。因此,您允许除空格以外的所有字符。
推荐阅读
- c# - 使用 PSCommands 获取进程 ID psexec
- python - 如何在 Flask 中设置 HTTPONLY cookie
- docker - 在 docker-compose 中强制临时端口绑定
- sql - 无法删除空值并接收输出
- php - 处理查询结果 - Quickbooks API PHP
- android - 如何在android中将json数据存储和提取到房间中
- javascript - 在一行代码中保存和解析用户输入?(Javascript)
- xml - XPath 给定节点文本匹配从子节点获取文本
- r - R:使用带有 grepl 条件的 if 语句处理列中的数据
- reactjs - 为什么我在 React JS 中的代码会进入满足这两个条件的无限循环?