user1669692
user1669692

Reputation: 119

How to Block Special Character in react?

Is there any samples , In blocking special character on key press or onblur event for react textArea box.

Since reactTextArea does have a call onClick event which calls the function to process the request in post method.

Upvotes: 3

Views: 29477

Answers (2)

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4244

We can use the following code too.

const checkSpecialChar =(e)=>{
  if(!/[0-9a-zA-Z]/.test(e.key)){
   e.preventDefault();
  }
 };

<input type='text' className='class' onkeyDown={(e)=>checkSpecialChar(e)}/>

Upvotes: 1

Tholle
Tholle

Reputation: 112787

You could use a regular expression for special characters and replace them all with an empty string.

Example

class App extends React.Component {
  state = { value: "" };

  onChange = event => {
    this.setState({ value: event.target.value.replace(/[^\w\s]/gi, "") });
  };

  render() {
    return <input value={this.state.value} onChange={this.onChange} />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 14

Related Questions