Reputation: 301
I have a text box where a user should enter his email id. How do I validate it that it accepts only email id and if email id does not contain '@' I want a message box to display enter valid email id
Upvotes: 0
Views: 1582
Reputation: 1508
<asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="regEmailId" runat="server"
ControlToValidate="txtEmailID" ErrorMessage="Invalid Email"
ValidationExpression="\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b"
ValidationGroup="Validate"></asp:RegularExpressionValidator>
<asp:Button id="btnEmailValidation" runat="server" ValidationGroup="Validate"
Text="Validate Email"/>
Upvotes: 0
Reputation: 1058
The best solution is to do a double check. The first one on client-side with JavaScript (see: JavaScript Regular Expression Email Validation) and the second one on the server side with a similar approach (see: how to make a validation code for ASP.NET form with VB coding).
Why two checks?
If you have only client-side validation, you can't ensure that the user is not changing the content just before sending the request to the server. The user can also have a browser without scripts compatibility or can have the scripts disabled.
If you have only server-side validation, you need to wait until the user press a button that causes a postbask and then check if the format is valid. If not, you need to refresh the page giving to him information about it. That is perfectly valid, but is not friendly since the user have to wait until he can see the server response and also some controls will lost the written information (eg, passwords fields).
Next time try to do some research before ask. There are several answers to this topic.
Upvotes: 1