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
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With