locked
Need help with regular expression for Name validations RRS feed

  • Question

  • Hi All,

    I need a regular expression with following requirements for Name validations.

    1. Name should contains atleast one alphabets.

    2. It may contains period, hyphen, apostraphe and space( may be multiple but not consecutive).

    Eg:

    Valid Strings: 

    test

    t.te-test test

    test-test'test.test, .test

    Invalid strings:

    test......test

    -.

    test----test

    I tried with below one, but no luck.

    ^(?!.*(.)\1)[\s.'-]*[a-zA-Z].*$

    Thanks in Advance.



    • Edited by vasiva Friday, May 9, 2014 11:48 AM
    Friday, May 9, 2014 11:45 AM

Answers

  • Hi, please try this:

    string pattern = @"^(?!.*(-{2,}|'{2,}| {2,}|\.{2,}))(?=.*[a-zA-Z])[a-zA-Z-\.' ]*$";

    Console.WriteLine(Regex.IsMatch("test", pattern));//true Console.WriteLine(Regex.IsMatch("t.te-test test", pattern));//true Console.WriteLine(Regex.IsMatch("test-test'test.test .test", pattern));//true Console.WriteLine(Regex.IsMatch("test-test'test.test, .test", pattern));//false Console.WriteLine(Regex.IsMatch("test......test", pattern));//false Console.WriteLine(Regex.IsMatch("-.", pattern));//false Console.WriteLine(Regex.IsMatch("test----test", pattern));//false


    • Marked as answer by Fred Bao Monday, May 19, 2014 7:43 AM
    Friday, May 9, 2014 6:00 PM