user5462581 user5462581 - 1 year ago 149
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.


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


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

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

Answer Source

You will have to change your regular expression to


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download