Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple function to Validate checkboxes in reactJS

I have made a selection limit function which ensures that total checkbox is above min value and under max value, these values were taken from the JSON which the checkboxes are mapped from, now the selection limit works, but I am trying to add validation to show warnings using onblur, but I am not sure how can the same function can be translated into an onblur validation function. for example where if someone unchecks , it shows on the console that you need to select a minimum of 3 until 3 is checked, same logic as selectData().

Function

  selectData(id, event) {
    let isSelected = event.currentTarget.checked;
    if (isSelected) {
      if (this.state.currentData < this.props.max) {
        this.setState({ currentData: this.state.currentData + 1 });
      } else {
        event.preventDefault();
        event.currentTarget.checked = false;
      }
    } else {
      if (this.state.currentData >= this.props.min) {
        this.setState({ currentData: this.state.currentData - 1 });
      } else {
        event.preventDefault();
        event.currentTarget.checked = true;
      }
    }
  }

Full Code: https://codesandbox.io/embed/48o2jo2500?fontsize=14

like image 913
AlxL Avatar asked Mar 13 '19 21:03

AlxL


1 Answers

Your general approach seems like it should work, just need the finesse for actually implementing the error states. A suggestion here though would be to update your !isSelected && this.state.currentData < this.props.min condition to allow for less than three to be selected but to display an error state to the user.

  ...
    } else {
      if (this.state.currentData >= this.props.min) {
        // this.setState({ currentData: this.state.currentData - 1 });
        // UPDATE:
        this.setState((state) => ({ currentData: state.currentData - 1 }));
      } else {
        event.preventDefault();
        // Don't force the box to be selected, show error state instead
        // Disable calls to filtering, sorting, etc. until error resolved
        // event.currentTarget.checked = true;
      }
    }
  }

Basic Implementation:

  • Vanilla JavaScript: https://codepen.io/hollyos/pen/XGqryV
  • React: https://codepen.io/hollyos/pen/EMpXdR
like image 92
HollyOS Avatar answered Sep 24 '22 11:09

HollyOS