Javascript validation regular expression for names

I'm looking to accept names in my application with letters and hyphens or dashes, I based my code on the answer I found here and encoded that:

function validName(n){
  var nameRegex = /^[a-zA-Z\-]+$/;
  if(n.match(nameRegex) == null){
    return "Wrong";
  }
  else{
    return "Right";
  }
}

the only problem is that it takes a hyphen as the first letter (even a few) that I don't want. thank

+4
source share
3 answers

You need to decompose your only character class into 2 by moving the hyphen outside and using the grouping construct to match the sequences of hyphen + alphanumeric characters:

var nameRegex = /^[a-zA-Z]+(?:-[a-zA-Z]+)*$/;

See regex demo

- (1 ) , 0 - + - .

1 , * ? (. regex).

- , - [\s-] (demo).

+1

lookahead, , . - , . - , - lookahead.

var nameRegex = /^(?!-)[a-zA-Z-]*[a-zA-Z]$/;
// or
var nameRegex = /^(?!-)(?!.*-$)[a-zA-Z-]+$/;

var nameRegex = /^(?!-)[a-zA-Z-]*[a-zA-Z]$/;
// or
var nameRegex1 = /^(?!-)(?!.*-$)[a-zA-Z-]+$/;

function validName(n) {
  if (n.match(nameRegex) == null) {
    return "Wrong";
  } else {
    return "Right";
  }
}

function validName1(n) {
  if (n.match(nameRegex1) == null) {
    return "Wrong";
  } else {
    return "Right";
  }
}

console.log(validName('abc'));
console.log(validName('abc-'));
console.log(validName('-abc'));
console.log(validName('-abc-'));
console.log(validName('a-b-c'));

console.log(validName1('abc'));
console.log(validName1('abc-'));
console.log(validName1('-abc'));
console.log(validName1('-abc-'));
console.log(validName1('a-b-c'));
Hide result

FYI: RegExp#test .

if(nameRegex.test(n)){
  return "Right";
}
else{
  return "Wrong";
}


:. - , 0 , -, @WiktorStribiżew.
var nameRegex = /^[a-zA-Z]+(?:-[a-zA-Z]+)*$/;
+3

You can use a negative lookup such as Pranav C Balan, or just use this simple expression:

^[a-zA-Z]+[a-zA-Z-]*$

Real-time example: https://regex101.com/r/Dj0eTH/1

0
source

Source: https://habr.com/ru/post/1669448/


All Articles