Search code examples
javascriptvalidationreactjsprecisiondecimal-point

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.

If the user enter a number like this: 1.234 it should prevent the user for entering more numbers despite typing on his keyboard. Any ideas as to how to implement this?


Solution

  • Like someone else suggested, use the onKeyDown event to limit the input. Quick and dirty example: 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();
        }
    }