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

191
Views
Improve JS Regex pattern for name validation

I am trying to create a regex pattern for name validation. Application name must have the following:

  1. Lowercase alphanumeric characters can be specified
  2. Name must start with an alphabetic character and can end with alphanumeric character
  3. Hyphen '-' is allowed but not as the first or last character e.g abc123, abc, abcd-1232

This is what I got [^\[a-z\]+(\[a-z0-9\-\])*\[a-z0-9\]$][1] it doesn't work perfectly. The validation fails if you enter a single character in the field. How can I improve this pattern? Thank you in advance.

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

0

You may use the following pattern:

^[a-z](?:[a-z0-9-]*[a-z0-9])?$

Explanation:

  • ^[a-z] starts with lowercase alpha
  • (?: turn off capture group
    • [a-z0-9-]* zero or more alphanumeric OR dash
    • [a-z0-9] mandatory end in alphanumeric only, if length > 1
  • )? make this group optional
  • $ end of input
about 4 years ago · Juan Pablo Isaza Report

0

You are using a negated character class [^ that matches 1 character, not being any of the specified characters in the character class.

That is followed by another character class [1] which can only match 1, so the pattern matches 2 characters, like for example #1


In your examples you seem to have only a single hyphen, so if there can not be consecutive hyphens --

^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$

Explanation

  • ^ Start of string
  • [a-z] Match a single char a-z
  • [a-z0-9]* Optionally repeat any of a-z or 0-9
  • (?:-[a-z0-9]+)* Optionally repeat matching - followed by at least 1 or a-z or 0-9 (So there can not be a hyphen at the end)
  • $ End of string

Regex demo

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!