0

I'd want to validate a username using a regular expression, however the expression I used worked well on https://regexr.com/  but not in my code. I just want user can add only Alphanumeric and a space between them

var letters = /^[A-Za-z]+$/g;

function validate() {
  var input = document.getElementById("fname").value;
  if (input.match(letters)) {
    document.getElementById("name").innerHTML = "** Only alphabets are allowed in name.";
    return false;
  }
}
<input id="fname">
<input type="button" onclick="validate()" value="Check">
<br>
<span id="name"></span>

12
  • 4
    It is usually a bad idea to limit user names, for example Peter O'Donelly-Smith might not be happy with that. Why do you need to limit user names? That might help us find a better solution for you. Commented Oct 8, 2021 at 17:45
  • I actually want to validate user names so that a user can input their names in the format "Ali Ahmed." Commented Oct 8, 2021 at 17:49
  • 1
    @AndrewMorton I don't agree... messy username will be a bad idea. Will look bad for other users, and will be annoying, if someone will exploit it. Every decent service does limit user names. Commented Oct 8, 2021 at 17:51
  • Does this answer your question? Regular expression "^[a-zA-Z]" or "[^a-zA-Z]" Commented Oct 8, 2021 at 17:51
  • 1
    @FlashThunder Try telling that to anyone who wants their name to be represented correctly, but the system does not allow it. Commented Oct 8, 2021 at 17:56

1 Answer 1

1

Your current function is "finding alphanumeric characters". So, when you run validate(), it is returning either a valid Array, or null. To get spaces use /^[\w\-\s]+$/ although this will return true for multiple spaces. I'm not sure your use case.

Unless you want to change your regex, you need to show your warning when input.match() returns a falsey value. To do this, Place ! before your input.match() function

var letters = /^[\w\-\s]+$/;

function validate() {
  document.getElementById("name").innerHTML = "";

  var input = document.getElementById("fname").value;

  if (!input.match(letters)) {
document.getElementById("name").innerHTML = "** Only alphabets are allowed in name.";
return false;
  }
}
<input id="fname">
<input type="button" onclick="validate()" value="Check">
<br>
<span id="name"></span>

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, guys I should have read the question more specifically instead of just bug-fixing the existing code. I will update or remove my answer.
Also, is this duplicate of stackoverflow.com/questions/13283470/… ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.