我有输入字段,我希望它是文本而不是数字。示例:姓名、名字
打字稿
this.etatCivilForm = formBuilder.group({
idCivilite: ['', Validators.required],
nomNaissance: ['', Validators.required],
prenom: ['', Validators.required, Validators.pattern('[^(0-9)]')],
nomUsage: [''],
.HTML
<mat-form-field>
<input matInput formControlName="prenom" tabindex="21" required autocomplete="off"
placeholder="{{'etatCivil.prenom'|translate}}" maxlength="50">
</mat-form-field>
<p *ngIf="etatCivilForm.controls.prenom.value.valid">prenom n'est pas valide</p>
<mat-form-field>
结果:什么都没有发生。
正如我在评论中提到的,pattern
只是检查值是否与正则表达式匹配,如果不匹配,则该字段被视为无效,但它不会阻止用户输入无效的值。您可以添加一个检查输入值的keypress
处理程序,如果确定,则返回该值,或使用 event.preventDefault
阻止输入。以下内容适用于仅添加字母和空格。如果您需要其他内容,请根据需要修改正则表达式。因此,请尝试以下操作:
<input formControlName="prenom"
(keypress)="checkValue($event)">
和功能:
checkValue(event) {
return String.fromCharCode(event.charCode).match(/^[a-zA-Zs]*$/) ?
event.CharCode : event.preventDefault();
}
演示
试试这个:
加
onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'
到输入字段。