Reputation: 14126
I am very new to Javascript.
I have a requirement to allow only digits and enter key as input in a textarea box
. I would also like to allow users to paste ONLY digits into the textarea
.
After searching through the questions on StackOverflow, I found the following:
function validate(key)
{
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('textarea');
//comparing pressed keycodes
if (keycode < 48 || keycode > 57)
{
return false;
}
<div>
<textarea id="textarea" rows="4" cols="50" onkeypress="return validate(event)" />
</div>
Unfortunately, this does not solve my problem completely. I want to allow users to press enter
. How can I change the above code to allow "enter" presses as well as integer paste events?
Upvotes: 1
Views: 7464
Reputation: 11
function validate(){
const input = document.getElementById("input")
const regex = /[^0-1|\n\r]/g
input.value = input.value.split(regex).join('');
}
Upvotes: 1
Reputation: 1170
This is a pretty easy modification. Just add an "is equal to" statement to your code. Also, since you also want to handle paste events, you'll need an event listener and function for "onPaste."
Method 1: Use "onPaste" Events
function validatepaste(e) {
var pastedata = e.clipboardData.getData('text/plain');
if (isNaN(pastedata)) {
e.preventDefault();
return false;
}
}
function validate(e) {
//getting key code of pressed key
var keycode = (e.which) ? e.which : e.keyCode;
var phn = document.getElementById('textarea');
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57) && keycode !== 13) {
e.preventDefault();
return false;
}
}
Here's a working fiddle
And here's some info on the "onPaste" event.
Method 2: Use "onKeyUp" instead of "onPaste" and "onKeyPress"
This method is less elegant, but it works if your environment doesn't support "onPaste"
function validate(e) {
var invalidcharacters = /[^0-9]/gi
var phn = document.getElementById('textarea');
if (invalidcharacters.test(phn.value)) {
newstring = phn.value.replace(invalidcharacters, "");
phn.value = newstring
}
}
<div>
<textarea id="textarea" rows="4" cols="50" onKeyUp="validate(event)"></textarea>
</div>
And a jsfiddle
Upvotes: 2
Reputation: 95
Your if statement should look something along the lines of if( keycode == 13 || keycode > x1 AND keycode < x2 || keycode > y1 AND keycode < y2) gives valid input else invalid input
Where x is the range of numbers for numbers, and y is the range of numbers for characters.
Upvotes: 0