Mih*_*ilo 31 forms validation angular
type="number"
如果仅使用Reactive Forms (无指令),如果值为numeric或null,我如何验证输入是否有效?
只有数字[0-9]
和.是允许的,没有"e"或任何其他字符.
到目前为止我尝试过的:
<form [formGroup]="form" novalidate>
<input type="number" formControlName="number" id="number">
</form>
Run Code Online (Sandbox Code Playgroud)
export class App {
form: FormGroup = new FormGroup({});
constructor(
private fb: FormBuilder,
) {
this.form = fb.group({
number: ['', [CustomValidator.numeric]]
})
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是当用户输入的东西不是数字("123e"或"abc")时,FormControl的值变为null
,请记住我不希望该字段是必需的,所以如果该字段确实为空null
值应该是有效.
跨浏览器支持也很重要(Chrome的数字输入字段不允许用户输入字母 - 除了"e",但FireFox和Safari确实如此).
Ish*_*awa 34
在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>
Run Code Online (Sandbox Code Playgroud)
在.ts文件中,您可以添加Validators模式 - "^ [0-9]*$"
this.Mobile = new FormControl('', [
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(8),
]);
Run Code Online (Sandbox Code Playgroud)
最简单的方法是使用像这样的库,特别是你想要noStrings
真实的
export class CustomValidator{ // Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});
if (hasError) return null;
return val;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46440 次 |
最近记录: |