user5462581 user5462581 - 3 months ago 15
HTML Question

Check if input contains an invalid character

I want to check if a user inputs an invalid character when chosing his name. My code almost works. The only problem is when I type in a valid user name f.e. "John" and add an invalid character to it "John!!" it doesn't detect it. When I type in an invalid character only "!!!!" it gets detected.

HTML:

<input class="user-input" pattern="[a-zA-Z0-9._-ßÄÖÜäöü]{1,30}" type="text" id="idUsername" oninput='checkValidUsername();'" required disabled>


JavaScript:

function checkValidUsername()
{
var input = document.getElementById("idUsername").value;

if(input.search(/^[a-zA-Z0-9ßÄÖÜäöü_.-]/) == -1)
{
document.getElementById("idValidChars").style.visibility = "visible";
}
else
{
document.getElementById("idValidChars").style.visibility = "hidden";
}
}

Answer

You will have to change your regular expression to

/^[a-zA-Z0-9ßÄÖÜäöü_.-]+$/

This is because you need to check the whole string for a validity, instead of the first character as you did.
The + allows the previous sequence to appear more than one occurrence, and the $ restricts it to be the end of the string. Which means, that the string must start and end with only the characters you have indicated.