How to prevent invalid characters from being typed into input fields

后端 未结 7 1754
猫巷女王i
猫巷女王i 2020-11-29 10:11

Onkeydown, I run the following JavaScript:

function ThisOnKeyDown(el) {
   if (el.title == \'textonly\') {
       !(/^[A-Za-zÑñ-\\s]*$/i).test(e         


        
7条回答
  •  一整个雨季
    2020-11-29 10:35

    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;
        }
    });
    

提交回复
热议问题