Search code examples
javascriptregexhtmlreactjsreact-redux

input pattern='[a-zA-Z]' is not working in React application


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>
    ); 
}

Solution

  • That's easy. You:

    1. Remove the pattern attribute.
    2. Register your onInputChange method for input events instead of change events (onInput={event => this.onInputChange(event.target.value)}).
    3. Clean up the received value in the onInputChange before changing the state.