Reputation: 3630
[RegularExpression("^([a-zA-Z-`])+$", ErrorMessage = "Please correct your First Name - this should not contain any special characters other than - or `.")]
public string FirstName { get; set; }
I have the above regex pattern to allow users to input alphabets, dash and backtick only. However I am not able to create a pattern to only allow an alphabet to be followed by the dash or apostrophe. eg:
valid: sam`s, abd-cdf, dbc-dfd`s
invalid: sam``s, abcd--cef, dbf-`dfd, dbf`-dfd
How can I make sure that the above two special characters: dash and backtick , if included in a string, should have alphabets only at pre and post occurrence.
Upvotes: 0
Views: 660
Reputation: 11912
You could use this
^([a-zA-Z]|(?<=[a-zA-Z])[`-])+$
Which will match any number of either
[a-zA-Z]
or
(?<=[a-zA-Z])[`-])
The second part uses a lookbehind which says that a backtick or -
must be preceeded by one of the character class [a-zA-Z]
Upvotes: 0
Reputation: 1150
Try this. It should work for you. Let me know if you have some other conditions as well.
^[a-zA-Z]+((`|-)[a-zA-Z]+)*$
Upvotes: 0
Reputation: 71578
First thing, you should avoid placing a dash (or hyphen) in between characters in a character class unless you want a range of characters. Since you want only backticks and hyphens, it would be better to use:
^[a-zA-Z`-]+$
Also, I don't think the capture group is necessary here.
On to the next requirement. You might want to use something like that:
^[a-zA-Z]+(?:[`-][a-zA-Z]+)*$
This is any number of letters, followed by either `
or -
and a nother series of letters, and makes the backtick and hyphen appear only in the middle of the string.
Upvotes: 1