Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

javascript - How to prevent invalid characters from being typed into input fields

Onkeydown, I run the following JavaScript:

function ThisOnKeyDown(el) {
   if (el.title == 'textonly') {
       !(/^[A-Za-z??-s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-z??-s]/ig, '') : null;
   }
   if (el.title == 'numbersonly') {
       !(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null;
   }
   if (el.title == 'textandnumbers') {
       !(/^[A-Za-z??0-9-s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-z??0-9-s]/ig, '') : null;
   }
}

One of these three title attributes is given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!

Edit: I create the events globally. Here's how I do that:

      function Globalization() {
      var inputs = document.getElementsByTagName('input');
      for (i = 0; i < inputs.length; i++) {
          inputs[i].onfocus = createEventHandler(
              ThisOnFocus, inputs[i]);
          inputs[i].onblur = createEventHandler(
              ThisOnBlur, inputs[i]);
          inputs[i].onkeydown = createEventHandler(
              ThisOnKeyDown, inputs[i]);
          inputs[i].onkeyup = createEventHandler(
              ThisOnKeyUp, inputs[i]);
      }
  }

Globalization() is run body.onload

Therefore, a typical input field has HTML without function calls like this:

          <input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating any further.

I wrote the example below using jQuery, but you can use the same function when binding traditionally.

Though it's important to validate on the server-side as well, client-side validation is important for the sake of user friendliness.

$("input.number-only").bind({
    keydown: function(e) {
        if (e.shiftKey === true ) {
            if (e.which == 9) {
                return true;
            }
            return false;
        }
        if (e.which > 57) {
            return false;
        }
        if (e.which==32) {
            return false;
        }
        return true;
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...