ASP.NET - help me with validation code - Asked By Gaurav on 21-Apr-11 02:51 AM

below is my registration design page...
having feilds
UserName
UserLogin
Password
RePassword
Address
Phone
Email

i want to validate each field...bt on clicking submit button it is storing data into a database
plz help me with code or idea to validate the fields such that data shd nt go into the database untill it is validated


<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="signup.aspx.cs" Inherits="signup" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .style2
        {
            height: 27px;
        }
    </style>
</asp:Content>



<asp:Content ID="Content3" ContentPlaceHolderID="Main" Runat="Server">
    <div>
<br />
<br />
<br />


</div>
    <div> <center><table border="2" cellpadding="4" style="height: 294px; width: 277px">
       <tr>
            <td colspan="2" class="style2"> 
                <asp:Label ID="Label4" runat="server" Text="Signup"></asp:Label>
            </td>
       </tr>
        <tr>
            <td align="left">
                <asp:Label ID="Label1" runat="server" Text="UserName"></asp:Label>
            
            </td>
            <td >
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="left">
                <asp:Label ID="Label7" runat="server" Text="UserLogin"></asp:Label>
            </td>
            <td >
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </td>
            
     
        </tr>
        <tr>
            <td align="left">
                <asp:Label ID="Label2" runat="server" Text="Psssword"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TextBox3" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr>
         <tr>
            <td align="left">
                <asp:Label ID="Label3" runat="server" Text="Re-Password"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="left">
                <asp:Label ID="Label8" runat="server" Text="Address"></asp:Label>
            </td>
            <td >
                <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="left">
                <asp:Label ID="Label5" runat="server" Text="Phone"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="left">
                <asp:Label ID="Label6" runat="server" Text="E-mail"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
            </td>
        </tr>
        
      
        <tr>
            <td align="left">
                <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click"  />
            </td>
            
            <td align="center">
                <asp:Button ID="Button2" runat="server" Text="Clear" onclick="Button2_Click" />
            </td>
        </tr>
        
    </table></center> </div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="Footer" Runat="Server">
</asp:Content>

  
TSN ... replied to Gaurav on 21-Apr-11 02:55 AM
Hi...
Refer the Below Code and Make neccesary chages to use in your form.........

In this just make a form as follows:

  1. Name : <asp:TextBox ID="txtName" />
  2. Email : <asp:TextBox ID="txtEmail" />
  3. Web URL : <asp:TextBox ID="txtWebUrl" />
  4. Zip : <asp:TextBox ID="txtZip" />
  5. <asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server" Text="Submit" />

Now on the source code of this form in script tag write the following code:

<script language="javascript" type="text/javascript">
function
validate()
{
    if (document.getElementById("<%=txtName.ClientID%>").value==""
)
    {
         alert("Name Feild can not be blank"
);
         document.getElementById(
"<%=txtName.ClientID%>"
).focus();
         return false
;
    }
    if(document.getElementById("<%=txtEmail.ClientID %>").value==""
)
    {
         alert(
"Email id can not be blank"
);
          document.getElementById("<%=txtEmail.ClientID %>"
).focus();
          return false
;
    }
   var
emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
   var emailid=document.getElementById("<%=txtEmail.ClientID %>"
).value;
   var
matchArray = emailid.match(emailPat);
   if (matchArray == null
)
    {
         alert(
"Your email address seems incorrect. Please try again."
);
         document.getElementById(
"<%=txtEmail.ClientID %>"
).focus();
         return false
;
    }
    if(document.getElementById("<%=txtWebURL.ClientID %>").value==""
)
    {
         alert(
"Web URL can not be blank"
);
         document.getElementById(
"<%=txtWebURL.ClientID %>").value=
"http://"
         document.getElementById("<%=txtWebURL.ClientID %>"
).focus();
         return false
;
    }
  var Url=
"^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
  var tempURL=document.getElementById("<%=txtWebURL.ClientID%>"
).value;
  var
matchURL=tempURL.match(Url);
   if(matchURL==null
)
   {
         alert(
"Web URL does not look valid"
);
         document.getElementById(
"<%=txtWebURL.ClientID %>"
).focus();
         return false
;
   }
   if (document.getElementById("<%=txtZIP.ClientID%>").value==""
)
   {
         alert(
"Zip Code is not valid"
);
         document.getElementById(
"<%=txtZIP.ClientID%>"
).focus();
         return false
;
   }
   var digits="0123456789"
;
   var
temp;
   for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>"
).value.length;i++)
   {
         temp=document.getElementById(
"<%=txtZIP.ClientID%>"
).value.substring(i,i+1);
         if
(digits.indexOf(temp)==-1)
         {
              alert(
"Please enter correct zip code"
);
              document.getElementById(
"<%=txtZIP.ClientID%>"
).focus();
              return false
;
         }
   }
   return true
;
}
</script>

And in code behind file just write the below code.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
         btnSubmit.Attributes.Add(
"onclick", "return validate()"
)
End Sub

shekhar kumar replied to Gaurav on 21-Apr-11 02:56 AM
Your should use either validation controls
or use javascript function on submit click.
Ravi S replied to Gaurav on 21-Apr-11 03:04 AM
HI

try with this example

<script type="text/javascript" >
function validate()
{
    var validate = "true";
    if(document.getElementById("<%=txtFirstName.ClientID%>").value == '')
 {
  document.getElementById("imgFirstName").style.display = 'block';
  //document.getElementById("<%=txtFirstName.ClientID%>").focus();
  validate = "false"; 
 }
  if(document.getElementById("<%=txtSurName.ClientID%>").value == '')
 {
  document.getElementById("imgLastName").style.display = 'block';
  validate = "false"; 
 }
  if(document.getElementById("<%=txtDOB.ClientID%>").value == '')
 {
  document.getElementById("imgDOB").style.display = 'block';
  validate = "false"; 
 }
  if(document.getElementById("<%=txtPhone.ClientID%>").value == '')
 {
  document.getElementById("imgPhone").style.display = 'block';
  validate = "false"; 
 }
   if(document.getElementById("<%=txtuserid.ClientID%>").value == '')
 {
  document.getElementById("imguserid").style.display = 'block';
  validate = "false"; 
 }
  if(document.getElementById("<%=txtEmailId.ClientID%>").value == '')
 {
  document.getElementById("imgEmailId").style.display = 'block';
  validate = "false"; 
 }
  if(document.getElementById("<%=txtPassword.ClientID%>").value == '')
 {
  document.getElementById("imgPassword").style.display = 'block';
  validate = "false"; 
 }
  if(document.getElementById("<%=txtConfirmPassword.ClientID%>").value == '')
 {
  document.getElementById("imgConfirmPassword").style.display = 'block';
  validate = "false"; 
 }
  if(document.getElementById("<%=txtuserid.ClientID%>").value == '')
 {
  document.getElementById("imguserid").style.display = 'block';
  validate = "false"; 
 }
 if(validate =='false')
 {
   return false;
 }
 if(validate =='true')
 {
   return true;
 }
}
</script>



<body >
    <form id="form1" runat="server" >
<table>
<tr>
          <td class="style16">
            <asp:Label ID="lblSurName" runat="server" CssClass="label" Font-Size="Medium"
              ForeColor="White" Text="Sur Name" Width="99px"></asp:Label>
          </td>
          <td class="style21">
            <asp:TextBox ID="txtSurName" runat="server" BorderStyle="Solid"
              CssClass="txtcss1" Font-Size="Medium" tooltipText="Enter Last Name"
              onBlur="setVisibilityText('imgLastName','txtSurName')"></asp:TextBox>
             <span id="imgLastName" style="display:none">
           <%-- <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSurName" ></asp:RequiredFieldValidator>--%>
    </td>
            <tr>
              <td class="style16">
                <asp:Label ID="lblDOB" runat="server" CssClass="label" Font-Size="Medium"
                  ForeColor="White" Text="Date of Birth" Width="100px"></asp:Label>
              </td>
              <td class="style21">
                <asp:TextBox ID="txtDOB" runat="server" BorderStyle="Solid" CssClass="txtcss1"
                  Font-Size="Medium" tooltipText="Enter DOB"
              onBlur="setVisibilityText('imgDOB','txtDOB')"></asp:TextBox>
              <span id="imgDOB" style="display:none"></span>
                <cc1:CalendarExtender ID="CalendarExtender1" runat="server"
                  TargetControlID="txtDOB"></cc1:CalendarExtender>
            
              </td>
            </tr>
            <tr>
              <td class="style16">
                <asp:Label ID="lblphone" runat="server" CssClass="label" Font-Size="Medium"
                  ForeColor="White" Text="Mobile"></asp:Label>
              </td>
              <td class="style21">
                <asp:TextBox ID="txtPhone" runat="server" BorderStyle="Solid"
                  CssClass="txtcss1" Font-Size="Medium" tooltipText="Enter Phone no"
              onBlur="setVisibilityText('imgPhone','txtPhone')">
              </asp:TextBox> <span id="imgPhone" style="display:none">
              
              </td>
            </tr>
>/table>

This is an example...edit according to your requirement
dipa ahuja replied to Gaurav on 21-Apr-11 03:47 AM
For Username:

 <asp:TextBox ID="UserName" runat="server"/>
  <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" 
  ToolTip="User Name is required."
  ErrorMessage="User Name is required." Text="*" 
 ControlToValidate="UserName"/>

For Password:

<asp:TextBox ID="Password" runat="server" TextMode="Password"/>
  <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" 
  ToolTip="Password is required."
    Text="*" ErrorMessage="Password is required." ValidationGroup="CreateUserWizard1" 
    ControlToValidate="Password"/>    

For re-enter password:
    <asp:TextBox ID="Password" runat="server"></asp:TextBox>
    
    <asp:CompareValidator ID="CompareValidator1"
      runat="server" ErrorMessage="Password not matched" ControlToCompare="Password" 
      ControlToValidate="RePassword"></asp:CompareValidator>
For Email:

  <asp:TextBox ID="Email" runat="server"/>
    
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
      runat="server" ControlToValidate="email"
      ErrorMessage="Email Addr Invalid" Font-Size="Smaller" Text="Invalid format"
      ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
      
    <asp:RequiredFieldValidator ID="EmailRequired" 
    runat="server" ToolTip="Email is required." Text="*"
    ErrorMessage="Email is required" ValidationGroup="CreateUserWizard1" 
    ControlToValidate="Email"/>

Hope this will help you!
   
Gaurav replied to dipa ahuja on 21-Apr-11 05:10 AM
thanks for the help maam ...it helped me...
bt some problem in password feild...ie it doent show red star on blank initiaaly bt shows once i go back...
can it be corrected...

and plz if u can provide validation for address and phone number too

thanx a lot