如何仅使用响应式表单(无指令)来验证 type="number"
的输入仅在值为数字或 null 时才有效?< br/>
只有数字 [0-9]
和 .是允许的,没有“e”或任何其他字符。
到目前为止我尝试了什么:
模板:
<form [formGroup]="form" novalidate>
<input type="number" formControlName="number" id="number">
</form>
组件:
export class App {
form: FormGroup = new FormGroup({});
constructor(
private fb: FormBuilder,
) {
this.form = fb.group({
number: ['', [CustomValidator.numeric]]
})
}
}
自定义验证器:
export class CustomValidator{
// Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
if (val === null || val === '') return null;
if (!val.toString().match(/^[0-9]+(\.?[0-9]+)?$/)) return { 'invalidNumber': true };
return null;
}
}
Plunker
问题是当用户输入的内容不是数字(“123e”或“abc”)时,FormControl 的值变为null
,记住我不'希望该字段是必需的,因此如果该字段确实为空 null
值应该有效。
Cross browser support is also important (Chrome's number input fields do not allow the user to input letters - except "e", but FireFox and Safari do).
最佳答案
在 HTML 文件中,您可以像这样为您的模式添加 ngIf,
<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
<p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
</div>
在 .ts
文件中,您可以添加验证器模式 -"^[0-9]*$"
this.Mobile = new FormControl('', [
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(8),
]);
关于forms - 输入类型编号 "only numeric value"验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057907/