horatio.mars
horatio.mars

Reputation: 569

javascript regex (username validation)

I want to enforce that

  1. the input firstname should only contains characters A-Z, a-z, and -
  2. the input login name should only contains alphanumeric characters

How do I restrict the two rules in javascript?

Below is my code (jsp) for username regex. But it's not working properly.

function validateForm(){
    var nameRegex = /^[a-zA-Z\-]+$/;
    var validfirstUsername = document.frm.firstName.value.match(nameRegex);
    if(validUsername == null){
        alert("Your first name is not valid. Only characters A-Z, a-z and '-' are  acceptable.");
        document.frm.firstName.focus();
        return false;
    }
}

Thanks!

Upvotes: 27

Views: 128841

Answers (3)

Amir
Amir

Reputation: 449

Usernames can only use letters, numbers, underscores, and periods.

  const onValidUsername = (val) => {
    const usernameRegex = /^[a-z0-9_.]+$/
    return usernameRegex.test(val)
  }

Upvotes: 9

Ben Winding
Ben Winding

Reputation: 11787

Here's the validation function I came up with, tailor it for your own use-cases:

function isUserNameValid(username) {
  /* 
    Usernames can only have: 
    - Lowercase Letters (a-z) 
    - Numbers (0-9)
    - Dots (.)
    - Underscores (_)
  */
  const res = /^[a-z0-9_\.]+$/.exec(username);
  const valid = !!res;
  return valid;
}

Upvotes: 10

Jason McCreary
Jason McCreary

Reputation: 72991

The code you have looks fine, aside from the inconsistent variable reference (see the comment by Josh Purvis).

The following regex is fine for your first name spec:

var nameRegex = /^[a-zA-Z\-]+$/;

Adding digits for your username check is straightforward:

var usernameRegex = /^[a-zA-Z0-9]+$/;

Note: There are many ways to write regular expressions. I've chosen to provide a version that matches what you started with. I encourage you to work through this Regular Expression Tutorial

Upvotes: 36

Related Questions