Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
How to validate user name with regular expression

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!