[英]Validation for html5 input type number
I would like to show 2 different validation messages for the following input type 我想针对以下输入类型显示2条不同的验证消息
<input type="number" step="1" formControlName="Ordinal" />
I'm using reactive forms with a formGroup that is similar to this 我正在使用具有与此类似的formGroup的反应形式
formBuilder.group({
..
Ordinal: [0, [Validators.required, CustomValidators.integer]],
..
});
One Validator Validators.required
should show a required message if there is no input at all. 如果根本没有输入,一个Validator
Validators.required
应该显示一条必填消息。 The other Validator Validator.integer
should show a message if an invalid number is entered. 如果输入了无效的号码,另一个Validator
Validator.integer
应该显示一条消息。
The current implementation of Validation.integer looks like this Validation.integer的当前实现如下所示
export function integer(control: FormControl) {
const value = control.value;
if ((parseFloat(value) === parseInt(value, 10)) && !isNaN(value) || value === '' || value === null) {
return null;
} else {
return {
notNumeric: true
};
}
}
My problem is that with type="number"
the browser returns null
in both cases (when input is empty / when number is invalid). 我的问题是,在两种情况下,如果使用
type="number"
,浏览器都将返回null
(当输入为空/ number无效时)。 How can i distinguish these two states? 我如何区分这两种状态?
to check numeric value I thinks `isNaN and Number.isInteger()` would be enough
Please check the following updated conditions :-
export function integer(control: FormControl) {
const value = control.value;
if(value === 'null' || value === undefined || value === '' ){
return isRequired: true
}
else if ((!Number.isInteger(value) || !isNaN(value))) {
return null;
} else {`enter code here`
return {
notNumeric: true
};
}
}
hope this helps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.