Home > Mobile >  How do i prevent entering in input any character except letters and one underscore in a row?
How do i prevent entering in input any character except letters and one underscore in a row?

Time:01-03

I can't create an input in which the first character entered must be a letter, and the following characters can be only letters or only one underscore in a row

i have an input and following javascript code for it:

var nick = document.getElementById('donate-nickname');

function validatenick(evt) {
    var regex = /^[a-zA-Z][a-zA-Z_]*$/;
    if(!regex.test(nick.value)) evt.preventDefault();
}

nick.onkeydown = validatenick;
nick.onpaste = validatenick;

but it doesn't work

CodePudding user response:

Some issues:

  • You are not assigning visited to onkeydown, but instead execute it. (You fixed this after I posted this answer)
  • input.value will reflect the input as it is before the key was processed, so the validation check comes too early.
  • The regex does not implement the logic you describe

I would suggest a regex where you perform a negative look-ahead for a double underscore. Also make it allow empty input as else the user cannot delete the last character that remains in the input.

For responding to all input methods, use the input event. Then to cancel the edit that would break the pattern, you could keep track of the most recent input that was still valid, and when there is a violation of the pattern, roll back to that value:

var input = document.getElementById('nickname');

var lastValid = "";

function validate(evt) {
    var regex = /^(?!_)(?!.*?__)[A-Za-z_]*$/;
    if(!regex.test(input.value)) {
        input.value = lastValid;
    }
    lastValid = input.value;
}

input.oninput = validate;
<input id="nickname">

As a side note, I would personally not block edits like that: users may wrongly think their keyboard is malfunctioning. It is better practice to let the user type what they want, but accompany it with feedback (coloring, an error message, ...).

  • Related