angularfreek
angularfreek

Reputation: 11

Regex to not allow '.', '_', '-' at String Start or End and should not have consecutive '.' and the rest all special characters should not be allowed

the output should be like

.test_test1-test - INVALID
test2_test-test. - INVALID
_test.test-test- - INVALID
test.test-test - VALID
test._test-test - INVALID

The current expression that i have is mentioned below

/^[a-zA-Z0-9](?![_.-]?[^\na-zA-Z0-9]{2}).*?[a-zA-Z0-9]$/gim

Upvotes: 0

Views: 1571

Answers (5)

angularfreek
angularfreek

Reputation: 11

/^(?!.*\.\.)[a-zA-Z0-9_-](?:[a-zA-Z0-9_.-]{0,62}[a-zA-Z0-9_-])?$/

This expression worked with all the scenarios mentioned.

Upvotes: 0

user12097764
user12097764

Reputation:

If the conditions are applied to the entire string first, it ends up like this :

/^(?![._-])(?!.*[._-]$)(?!.*[._-][._-])[\w.-]*$/

https://regex101.com/r/hnVimE/1

Explained

 ^                         # BOS
 (?! [._-] )               # Not . or _ or - at beginning
 (?! .* [._-] $ )          # Not . or _ or - at end
 (?! .* [._-] [._-] )      # No consecutive  . or _ or - 
 [\w.-]*                   # Not special characters, except  . or _ or -
 $                         # EOS

This is set to match the empty string [\w.-]*, set the quantifier to +
if text is a requirement also.

Upvotes: 0

R. Schifini
R. Schifini

Reputation: 9313

You could also use:

^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$

and then negate the result:

rg = new RegExp('^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$','gim')
!rg.test('test.test-test')

Examples:

rg = new RegExp('^[^a-z0-9]|[_.-]{2,}|[^a-z0-9]$','gim')

console.log('Valid')
console.log('test.test-test', !rg.test('test.test-test'))

console.log('Invalid')
console.log('.test.test-test', !rg.test('.test.test-test'))

More examples here

Upvotes: 0

Nicolas
Nicolas

Reputation: 8670

Your regex seams to be a little bit complicated for what you are trying to do.

You have two part to your regex:

  • The first one is the test plus a symbole, that repeat twice.
  • The second one is the test but no symbol, that end the regex.

Also, you don't need to validate A-Z in your match group since your regex has an case insencitive flag.
Here is a working example :

/^([a-z0-9]+[._-]?){2}([a-z0-9]+)$/gmi

You can test more cases here

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30995

I can come up with a regex like this:

^[a-z]+(?:-[a-z]+)*(?:\.[a-z]+(?:-[a-z]+)*)+$

Working demo

enter image description here

However, this will generate a lot of backtracking and it will be slow if strings are long

I think the best solution for you is to split the string by . and then validate that each string matches the pattern of ^[a-z]+(?:-[a-z]+)*$

Upvotes: 2

Related Questions