Reputation: 317
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)}
/>
Upvotes: 1
Views: 3062
Reputation: 849
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()
}
}
Upvotes: 6