[英]Prevent user from entering a float number, greater than 3 decimals
I have an input field using react with this code: 我有一个使用此代码的输入字段:
const InputField = props => (
<div className="input-row">
<input
{...props.input}
type={props.type}
className="form-control input-box__input"
placeholder={props.placeholder}
value={props.value}
defaultValue={props.defaultValue}
defaultChecked={props.defaultChecked}
disabled={props.disabled}
onChange={props.onChange}
checked={props.checked}
/>
{props.meta.touched && props.meta.error &&
<span className="error">
{props.intl.formatMessage({ id: props.meta.error }) }
</span>}
</div>
);
I want to add a validation
or better a preventDefault
property so that it won't let the user entering a floating number with more than three decimal points. 我想添加一个
validation
或更佳的preventDefault
属性,以免用户输入具有三个以上小数点的浮点数。
If the user enter a number like this: 1.234 it should prevent the user for entering more numbers despite typing on his keyboard. 如果用户输入的数字是这样的:1.234,即使在键盘上打字,它也应防止用户输入更多的数字。 Any ideas as to how to implement this?
关于如何实现这一点的任何想法?
Like someone else suggested, use the onKeyDown event to limit the input. 像其他建议的一样,使用onKeyDown事件来限制输入。 Quick and dirty example: https://jsfiddle.net/bv9d3bwk/2/
快速而肮脏的示例: https : //jsfiddle.net/bv9d3bwk/2/
const InputField = props => (
<div className="input-row">
<input
{...props.input}
type={props.type}
className="form-control input-box__input"
placeholder={props.placeholder}
value={props.value}
defaultValue={props.defaultValue}
defaultChecked={props.defaultChecked}
disabled={props.disabled}
onChange={props.onChange}
onKeyDown={this.onKeyDown}
checked={props.checked}
/>
{props.meta.touched && props.meta.error &&
<span className="error">
{props.intl.formatMessage({ id: props.meta.error }) }
</span>}
</div>
);
const onKeyDown = (e) => {
const decimal_index = e.target.value.indexOf('.');
if(decimal_index > -1){
var decimals = e.target.value.substring(decimal_index, e.target.value.length+1);
if(decimals.length > 4 && e.keyCode !== 8){
e.preventDefault();
}
//this.props.onChange();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.