user5462581
user5462581

Reputation: 159

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

Upvotes: 0

Views: 2034

Answers (2)

Try this:

$('#ID').keydown(function (e) {
  if (e.shiftKey || e.ctrlKey || e.altKey) {
    e.preventDefault();
  } else {
    var key = e.keyCode;
    if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 &&             key <= 90))) {
      e.preventDefault();
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ID" type="text"  />

Upvotes: 0

Slavik Meltser
Slavik Meltser

Reputation: 10361

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.

Upvotes: 4

Related Questions