What I have been working on is a text input
that narrows down <option>
in a <select>
as the user types. It is working, but my concern now is security, what a user passes into the input
, and potential malicious entries.
I figured I could do something like <input placeholder='[a-zA-Z]' />
but it is still allowing other characters to be entered into the text box.
What am I doing wrong here, and what would be an alternative that would permit only alphanumeric being entered?
onInputChange(term) {
this.setState({ term });
}
renderOptionsSelect(term) {
return _.map(this.props.pos_list, p => {
var searchTerm = this.state.term.toLowerCase();
if (p.pos_code.toLowerCase().match(searchTerm)) {
return (
<option key={p.pos_code} value={p.pos_code}>{p.pos_code}</option>
);
}
});
}
// render the main element of the container
render() {
return (
<div className='panel panel-default'>
<div className='panel-heading'>
<h4><strong>Basic Query</strong></h4>
</div>
<div className='panel-body'>
<input
pattern='[a-zA-Z]'
className='form-control'
placeholder='Enter Keyword or Position Code'
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)}
/>
<hr />
<h4>Position:</h4>
<select className='form-control'>
<option></option>
{this.renderOptionsSelect()}
</select>
<br />
<h4>Data Cut:</h4>
<select className='form-control' disabled={true} />
</div>
</div>
);
}
To get the value of an input on button click in React: Declare a state variable that tracks the value of the input field. Add an onClick prop to a button element. When the button is clicked, update the state variable.
To reset a file input in React, set the input's value to null in your handleChange function, e.g. event. target. value = null . Setting the element's value property to null resets the file input.
Basic idea is: Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.
That's easy. You:
onInputChange
method for input
events instead of change
events (onInput={event => this.onInputChange(event.target.value)}
).onInputChange
before changing the state.Check my answer in details here: https://stackoverflow.com/a/68052651/13607767
Here it is in brief -
State
const [tagInputVal, setTagInputVal] = useState("");
Input tag
<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>
Handler function
function onChangeTagInput(e) {
setTagInputVal(e.target.value.replace(/[^a-zA-Z\d]/ig, ""));
}
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