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
2 Answers
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.

- 1
- 1

- 1,026
- 14
- 32
<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"/>

- 1,026
- 14
- 32

- 1,408
- 2
- 27
- 48
-
Do you want to validate on code behind or do you want to validate email address on client side (Using regular expression)? – Praveen Mitta Mar 18 '13 at 13:43
-
on the client side i want to validate i tried the following code but it is not working Function IsEmail(ByVal email As String) As Boolean Static emailExpression As New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$") Return emailExpression.IsMatch(email) End Function – user1795999 Mar 18 '13 at 13:53
-
@user1795999: I have added sample code. Tested and its working. – Praveen Mitta Mar 18 '13 at 14:03
-
@user1795999: The code which i posted does a client side validation for Email address. Did you try my code? – Praveen Mitta Mar 18 '13 at 14:21
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26385/discussion-between-user1795999-and-computergeek) – user1795999 Mar 18 '13 at 14:30