JavaScript Validation for User Name and Email Id in Asp.Net
Validate User Name and Email Id in a web page using JavaScript validation in ASP.Net. In this example I am using two TextBoxes. The first TextBox accepts user name and second textbox accepts email id.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmailValidation.aspx.cs" Inherits="EmailValidation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Vallidation on UserName and EmailId</title>
<script type="text/javascript">
function Validate() {
var msg = "";
msg += UserNameValidation();
msg += EmailIdValidation();
if (msg != "") {
alert(msg);
return false;
}
else {
alert("User Name and Email Id submited successfully");
return true;
}
}
function UserNameValidation() {
var id;
var controlId = document.getElementById("<%=txtusername.ClientID%>");
id = controlId.value;
var val = /^[a-zA-Z ]+$/
if (id == "") {
return ("Please Enter UserName" + "\n");
}
else if (val.test(id)) {
return "";
}
else {
return ("UserName accepts only spaces and charcters" + "\n");
}
}
function EmailIdValidation() {
var id;
var controlId = document.getElementById("<%=txtemailid.ClientID %>");
id = controlId.value;
var val = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
if (id == "") {
return ("Please Enter Email Id" + "\n");
}
else if (val.test(id)) {
return "";
}
else {
return ("Email Id should be in this form for example: amit@kumar.com" + "\n");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3 style="color:blue">Validation for User Name and Email Id in JavaScript</h3>
<table style="border-color: #333300; z-index: 1; left: 15px; top: 54px; position: absolute; height: 122px; width: 261px">
<tr>
<td>
<asp:Label ID="lblusername" runat="server" Text="UserName"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblemailid" runat="server" Text="Email Id"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtemailid" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClientClick ="Validate()" Font-Bold="True" />
</td>
</tr>
</table>
</form>
</body>
</html>
0 Comment(s)