I used the following regular expression:
[RegularExpression(@"^(Mr. .*|MR. .*|MRS. .*|Mrs. .*|MS. .*|Ms. .*|DR. .*|Dr. .*)", ErrorMessage = "Greeting must begin with Mr., Mrs., Ms., or Dr. and be followed by a name.")]
public string? Greeting { get; set; }
How can I force user to enter space after Mr.
, MR.
, MRs.
, Mrs.
, then at least one character after the space.
For example: if they enter Mr. Joe Doe
or Mr. Joe
is valid but they enter Mr.
with space only or Mr.
without space is invalid.
4
Answers
Couple of issues
.
matches "any character" so sayingMr.
allows someone to writeMra
Mrb
etc – put abefore it or put it in a character class (surround it with
[
]
)*
means "zero or more of" so a regex ofMr. .*
allows them to write zero characters for the name. To quantify "one or more" we use+
instead of*
If you want to do away with repetitive elements you could
The first one takes care of Mr and Ms, second takes care of Mrs, third Dr, then is the common element of "literally a period" followed by a succession of word characters
Try to replace every * with +
I believe this could help.
You can try something like this to get started
This should match the use cases you gave.
The backslash escapes the period so it matches a literal period.
The curly brackets give a range of how many patterns are allowed of the grouping before it.
The question mark makes the bracket grouping before it optional.
Also, give this site a shot to try out your regex in real time. https://regexr.com/
Use
See proof.
EXPLANATION