I have 2 ASP.NET regular expression validators:
^\s*[- .'\w] @\w (?:[-.]\w )*\.(?!co\s*$)\w{2,}\s*$
check whether the email address is valid@(adres.pl|vp.pl)
check if value contains any of these strings
The problem now is: The strings in bullet 2 above should NOT be allowed, so o email address "[email protected]" should not be allowed.
However, the validators are only positive, meaning that they check if they DO contain the structure. So when someone currently enters "[email protected]", I get "invalid value"
My code below:
<asp:TextBox ID="tbEmail" runat="server" />
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="emailinvalid" ValidationExpression="^\s*[- .'\w] @\w (?:[-.]\w )*\.(?!co\s*$)\w{2,}\s*$" ID="rev1" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="@(adres.pl|vp.pl)" ID="rev2" runat="server"/>
I was initially thinking of combining expressions 1 and 2, but then I wouldn't know which one fails, and don't know which error to display.
What I would expect is:
- "35435gd" -> emailinvalid
- "[email protected]" -> not allowed
- "[email protected]" -> all validators are ok
Or perhaps validator rev2
should only execute if rev1
does not throw an error, so "stacking" for a lack of a better term, which a: seems cumbersome and b: I wouldn't know how to do it.
How can I solve for this?
UPDATE 1
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[- .'\w] @(?!(?:adres|vp)\.pl\b)\w (?:[-.]\w )*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="@(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
"gddg" results in "not allowed", whereas I'd expect "invalid".
When I switch the order of these validators, both errors "invalid" and "not allowed" show.
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[- .'\w] @(?!(?:adres|vp)\.pl\b)\w (?:[-.]\w )*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="@(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
CodePudding user response:
You can use a single pattern and you might write your existing pattern as:
^\s*[- .'\w] @(?!(?:adres|vp)\.pl\b)\w (?:[-.]\w )*\.(?!co\s*$)\w{2,}\s*$
The part excluding either adres.pl
or vp.pl
can be written as @(?!(?:adres|vp)\.pl\b)
excluding those matches directly after the @.
You could also use @(?!(?:adres|vp)\.pl\s*$)
if that is the last part of the email address just like you currently do for this part \.(?!co\s*$)
See a regex demo.
Note that your pattern would allow leading and trailing whitespace chars for the e-mail address.