3

I want to validate string with rules:

  • string must contain at least one letter
  • string can contain only those symbols(but it's not a must): ' , - , ( , )
  • if there is a symbol present in the string, it must also contain a letter(at least one 1st bullet)
  • only symbols are not allowed

so far I have come up with the following regex:

    static personName = XRegExp.cache("^[\\s\\p{L}\\'\\-\\(\\)]+(?=\\S*\\p{L})\\S+$");

which doesn't work correctly. Only "^(?=\\S*\\p{L})\\S+$" this helps with the letters, I struggle to understand how to add symbols to it so that all rules will be passed, what am I doing wrong?

2 Answers2

1

If the chars you allow are restricted to those you enumerated you may use

var regex = XRegExp("^[\\s'()-]*\\p{L}[\\s\\p{L}'()-]*$"); 

If you want to allow any chars but only a subset of symbols, with "at least 1 letter" restriction use

var regex = XRegExp("^[\\p{N}\\s'()-]*\\p{L}[\\p{L}\\p{N}\\s'()-]*$"); 

See the JS demo:

var regex = XRegExp("^[\\s'()-]*\\p{L}[\\s\\p{L}'()-]*$");
console.log( regex.test("Sóme (unknown-string) doesn't like it") );

var regex = XRegExp("^[\\p{N}\\s'()-]*\\p{L}[\\p{L}\\p{N}\\s'()-]*$"); 
console.log( regex.test("Sóme unknown-string (123)") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>

Details

  • ^ - start of string
  • [\\s'()-]* - 0 or more whitespaces, ', (, ) or - chars
  • [\\p{N}\\s'()-]* - 0 or more digits, whitespaces and the allowed symbols
  • \\p{L} - a letter
  • [\\s\\p{L}'()-]* - 0 or more whitespaces, letters, ', (, ) or - chars
  • [\\p{L}\\p{N}\\s'()-]* - 0 or more letters, digits, whitespaces and the allowed symbols
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
-1

Try this regex

 ^[a-zA-Z0-9\'\-\(\)]*[a-zA-Z][a-zA-Z0-9\'\-\(\)]*$

Demonstration

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72