我有输入字段,但希望它是文本而不是数字。示例:名字,名字
TypeScript
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>
结果:什么也没发生。
答案 0 :(得分:1)
正如我在评论中提到的,pattern
仅检查该值是否与正则表达式匹配(如果不匹配),则将该字段视为无效,但不会阻止用户输入无效的值。您可以添加一个keypress
处理程序来检查输入的值,如果可以,返回该值,或使用event.preventDefault
阻止输入。以下仅添加字母和空格。如果您还需要其他内容,请根据需要修改正则表达式。因此,请尝试以下操作:
<input formControlName="prenom"
(keypress)="checkValue($event)">
和功能:
checkValue(event) {
return String.fromCharCode(event.charCode).match(/^[a-zA-Z\s]*$/) ?
event.CharCode : event.preventDefault();
}
答案 1 :(得分:0)
尝试一下:
添加
onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'
输入字段。