Data annotation for Salutation

How can I add Data Annotation for Salutation?
A salutation must begin with Dear Sir or Madam, Mr, Mrs, Dr in lower or uppercase?

I tried the following but it not working for me:

[RegularExpression(@"^(Dr|Mrs?|Ms). [A-Za-z] ([A - Za - z] (s|.|_)?)+[a-zA-Z]*$", ErrorMessage = "Greeting must begin with Mr., Mrs., Ms., or Dr")]


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use something like this: ^(Mr|Mrs|Ms|Dr). [p{L} '-]+$. The assumption is that a surname can contain letters, not necessarily basic Latin (p{L}), spaces in strict sense, apostrophes and hyphens. I did not add underscores. In the future you will probably need to extend this set.

This regular expression assumes that the salutation is all that is fed to to regular expression (i.e., that only salutation is subject to data annotation). If you check the whole letter, replace the final $ with an n (newline); and if there can be an address before the salutation, replace the initial ^ with (?:^|n). These newlines make sure that the salutation occupies a separate string. Do not use multiline option in this case.

Is the letter is user input, allow for extra spaces: ^s*(Mr|Mrs|Ms|Dr).[ ]+[p{L} '-]+$.

Also, the full stop after the title can be missing, so: ^s*(Mr|Mrs|Ms|Dr).? [ ]+[p{L} '-]+$.

You may want to add an optional final comma: ^s*(Mr|Mrs|Ms|Dr).?[ ]+[p{L} '-]+,?s*$.

Possible titles are also numerous, like Prof. or military ranks.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x