admin管理员组

文章数量:1399188

I want to only allow letters of the alphabet and numbers to be entered in a form field. I have tried many variations using regex, etc. and I cannot disable the space key or any special character keys.

Here is the latest copy of my code:

document.querySelector('#upperCase').addEventListener('keyup', function(e) {
  console.log(this.value);
  if (e.which == '32') return false;
  this.value = this.value.toUpperCase();
});
#upperCase {
  text-transform: uppercase;
}
<form>
  <input id="upperCase" maxlength="10" name="upperCase" type="text">
</form>

I want to only allow letters of the alphabet and numbers to be entered in a form field. I have tried many variations using regex, etc. and I cannot disable the space key or any special character keys.

Here is the latest copy of my code:

document.querySelector('#upperCase').addEventListener('keyup', function(e) {
  console.log(this.value);
  if (e.which == '32') return false;
  this.value = this.value.toUpperCase();
});
#upperCase {
  text-transform: uppercase;
}
<form>
  <input id="upperCase" maxlength="10" name="upperCase" type="text">
</form>

Is it possible to only allow letters and number to be keyed into an input text box?

Here is my jsfiddle: https://jsfiddle/bcjg7osr/29/

Share Improve this question edited Sep 6, 2018 at 0:49 Syfer 4,5093 gold badges22 silver badges38 bronze badges asked Sep 5, 2018 at 20:21 jdoejdoe 531 silver badge4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

One way you can do it is using the pattern attribute on your input. The only problem with the patter attribute is that it won't disallow spaces until the form is submitted, in which case the submission won't work and the user will be asked to change the input. This will only allow letters and numbers.

<input pattern = "[A-Za-z0-9]" id="upperCase" maxlength="10" name="upperCase" 
type="text">

本文标签: javascriptHow to disable or prevent the space key entry on web formStack Overflow