Preventing invalid characters from being entered in fields: A comprehensive guide
P粉124890778
P粉124890778 2023-08-27 21:06:52
0
2
412

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 assigned to each input field on the page. The code works as long as the invalid characters are removed correctly, but not until the next character is entered. I'd like to find a way to simply reject invalid input. thanks for your help!

Edit: I create events globally. This is what I did:

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()runbody.onload

So a typical input field has HTML and no function calls like this:

 ;


P粉124890778
P粉124890778

reply all (2)
P粉034571623

The code above does illustrate this - only numbers are allowed. You can modify it by adding exceptions like this BACKSPACE


           sssccc
    P粉807471604

    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 further.

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

    Although server-side validation is also important, client-side validation is also important for 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; } });
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!