1

i have input field to place a phone number and i want to restrict every special character like

+,- .

from my input field with onPaste event. My code below is not working, i still can paste those special character to my input field

onPaste(e) {
  let str = e.target.value;
  let newstr = str.replace(/[+-.]/g, '');
  if (str !== newstr) {
  e.preventDefault();
 }}

my input code

<InputText
  name="officePhone"
  placeholder="Office Phone"
  label="Office Phone"
  type="number"
  onChange={e => this.onChange(e, 'form')}
  value={this.state.form.officePhone}
  onPaste={e => this.onPaste(e)}
/>
2
  • 2
    What's the issue? Commented May 11, 2017 at 18:19
  • my code above is not working , i still able to paste those special character to my input field Commented May 11, 2017 at 18:30

1 Answer 1

6

Your onPaste function is looking at the e.target.value, what it needs to be getting is the pasted data from the clipboard which you get by using e.clipboardData.getData('Text').

onPaste(e) {
  const str = e.clipboardData.getData('Text');
  const newStr = str.replace(/[+-.]/g, '');
  if (str !== newStr) {
    e.preventDefault()
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't the onPaste(e) function also change the component state? Since the value of <InputField /> is set to this.state.form.officePhone
I am assuming he/she will come across this and add it to state later. I am unaware of how he/she is implementing the logic in the bigger picture.
@JustinOber getting error "TypeError: Cannot read property 'detData' of undefined"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.