Wednesday, 11 December 2019

asp.net Validation 

Sample .....


<div class="col-sm-6">
                                <div class="form-group">
                                    <asp:TextBox ID="txtName" runat="server" CssClass="form-control" placeholder="Name*"></asp:TextBox>
                                </div>
                            </div>

<div class="col-sm-6">
                                <div class="form-group">
                                    <asp:TextBox ID="txtPhoneNumber" runat="server" CssClass="form-control" placeholder="Mobile*" MaxLength="10"></asp:TextBox>
                                </div>
                            </div>

<div class="col-sm-6">
                                <div class="form-group">
                                    <asp:TextBox ID="txtEMail" runat="server" CssClass="form-control" placeholder="Email Address*"></asp:TextBox>
                                </div>
                            </div>

 <div class="col-sm-6">
                                <div class="form-group">
                                    <asp:TextBox ID="txtPANNUMBER" runat="server" CssClass="form-control" placeholder="PAN Number" MaxLength="10"></asp:TextBox>
                                </div>
                            </div>

<div class="col-sm-12">
                                <div class="form-group">
                                    <asp:TextBox ID="txtADDRESS1" runat="server" CssClass="form-control" placeholder="Address" TextMode="MultiLine" Rows="4"></asp:TextBox>
                                </div>
                            </div>

<div class="col-sm-6">
                                <div class="form-group">
                                    <asp:TextBox ID="txtPINCODE" runat="server" CssClass="form-control" placeholder="Pin Code" MaxLength="6"></asp:TextBox>
                                </div>
                            </div>


<div class="col-sm-6">
                                <div class="form-group">
                                    <asp:DropDownList ID="ddlDPType" runat="server" CssClass="form-control">
                                        <asp:ListItem Value="0" Text="--Select DP Type--">--Select DP Type--</asp:ListItem>
                                        <asp:ListItem Value="1" Text="CDSL">CDSL</asp:ListItem>
                                        <asp:ListItem Value="2" Text="NSDL">NSDL</asp:ListItem>
                                    </asp:DropDownList>
                                </div>
                            </div>

.............................................................................................................................................

<div class="clearfix"></div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <asp:Button ID="btnSubmit" runat="server" Text="SUBMIT" CssClass="btn-submit" OnClick="btnSubmit_Click" />
                                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False" />

                                    <div style="height: 1px; overflow: hidden">
                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" Text="*" SetFocusOnError="True" ErrorMessage="Name required" Display="Dynamic" ForeColor="red"></asp:RequiredFieldValidator>
                                        <ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" Enabled="True" TargetControlID="txtName" FilterType="LowercaseLetters,UppercaseLetters,Custom" ValidChars=".- ()"></ajaxToolkit:FilteredTextBoxExtender>

                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtPhoneNumber" Text="*" SetFocusOnError="True" ErrorMessage="Mobile required"></asp:RequiredFieldValidator>
                                        <ajaxToolkit:FilteredTextBoxExtender ID="txtPhone_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtPhoneNumber" FilterType="Numbers" ValidChars="."></ajaxToolkit:FilteredTextBoxExtender>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator2" ValidationExpression="[a-zA-Z0-9]{10}" runat="server" ControlToValidate="txtPhoneNumber" ErrorMessage="Phone number should be 10 digit">*</asp:RegularExpressionValidator>

                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtEmail" Text="*" SetFocusOnError="True" ErrorMessage="Email address required"></asp:RequiredFieldValidator>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Incorrent email" ControlToValidate="txtEmail" SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>


                                        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPANNUMBER" Text="*" SetFocusOnError="True" ErrorMessage="PAN Card Number required"></asp:RequiredFieldValidator>--%>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator3" ValidationExpression="[A-Z]{5}\d{4}[A-Z]{1}" runat="server" ControlToValidate="txtPANNUMBER" ErrorMessage="Please enter Valid PAN Card Number">*</asp:RegularExpressionValidator>

                                        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtADDRESS1" Text="*" SetFocusOnError="True" ErrorMessage="Address1 requered"></asp:RequiredFieldValidator>--%>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator4" ValidationExpression="[0-9a-zA-Z #,(,),/,-]+" runat="server" ControlToValidate="txtADDRESS1" ErrorMessage="please enter Valid Address1 ">*</asp:RegularExpressionValidator>

                                        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtADDRESS2" Text="*" SetFocusOnError="True" ErrorMessage="Address2 requered"></asp:RequiredFieldValidator>--%>
                                       <%-- <asp:RegularExpressionValidator ID="RegularExpressionValidator5" ValidationExpression="[0-9a-zA-Z #,(,),/,-]+" runat="server" ControlToValidate="txtADDRESS2" ErrorMessage="Please enter Valid Address2 ">*</asp:RegularExpressionValidator>--%>

                                        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtPINCODE" Text="*" SetFocusOnError="True" ErrorMessage="PIN Code requered"></asp:RequiredFieldValidator>--%>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator6" ValidationExpression="[0-9]{6}" runat="server" ControlToValidate="txtPINCODE" ErrorMessage="Please enter Valid PIN Code ">*</asp:RegularExpressionValidator>

                                      
                                        <%--<asp:RequiredFieldValidator iD="RequiredFieldValidator12" runat="server" ControlToValidate="ddlCategory" ErrorMessage="Please Select a Category" InitialValue="0"></asp:RequiredFieldValidator>

                                        <asp:RequiredFieldValidator iD="RequiredFieldValidator8" runat="server" ControlToValidate="ddlDPType" ErrorMessage="Please Select a Type" InitialValue="0"></asp:RequiredFieldValidator>
                                       
                                        <asp:RequiredFieldValidator iD="RequiredFieldValidator9" runat="server" ControlToValidate="ddlBankName" ErrorMessage="Please Select a Bank Name" InitialValue="0"></asp:RequiredFieldValidator>--%>


                                        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ControlToValidate="txtDPNo" Text="*" SetFocusOnError="True" ErrorMessage="DP Number requered"></asp:RequiredFieldValidator>--%>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator8" ValidationExpression="[IN]{2}[0-9]{14}|[0-9]{16}" runat="server" ControlToValidate="txtDPNo" ErrorMessage="Please enter Valid DP Number">*</asp:RegularExpressionValidator>


                                       <%-- <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="txtAccNo" Text="*" SetFocusOnError="True" ErrorMessage="Bank A/C Number requered"></asp:RequiredFieldValidator>--%>
                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator7" ValidationExpression="[0-9]{9,20}" runat="server" ControlToValidate="txtAccNo" ErrorMessage="Please enter Valid Bank A/C Number">*</asp:RegularExpressionValidator>

                                    
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <a href="ipo.aspx" class="btn-reset" style="text-align: center"  onclick="clearControls" >RESET</a>
                                </div>
                            </div>

Login page example...

sample
********************** login-reports.aspx  *******************

<%@ Page Title="" Language="C#" MasterPageFile="~/Master.master" AutoEventWireup="true" CodeFile="login-reports.aspx.cs" Inherits="login-reports" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head1" runat="Server">

<title> page Title  </title>
    <style>
        .big-header .sub-nav li a {
            padding: 20px 28px;
        }
    </style>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="pageContent1" runat="Server">
   
    <div class="container">
        <div class="row">

            <div class="col-sm-4 col-sm-offset-4">
                <div style="margin: 100px 0 100px 0; border: 1px solid #ddd; padding: 20px">
                    <h2 style="text-align: center">Sign In</h2>
                    <br />
                    <div class="form-horizontal">
                        <div class="form-group">
                            <label class="control-label col-sm-3">User ID</label>
                            <div class="col-sm-9">
                                <asp:TextBox ID="txtUserID" runat="server" CssClass="form-control" ></asp:TextBox>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-3">Password</label>
                            <div class="col-sm-9">
                                <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" CssClass="form-control" ></asp:TextBox>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-offset-3 col-sm-9">
                                <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" CssClass="btn btn-danger" />
                                <!--<span style="padding-left: 20px"><a href="/recover-password">Forget Password</a></span>-->
                                <br />
                                <br />
                            </div>
                        </div>
                    </div>
                    <asp:Literal ID="ltrMsg" runat="server"></asp:Literal>
                </div>
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="footer1" runat="Server">
</asp:Content>


********************** login-reports.cs *******************


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtUserID.Focus();
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        //string strCon = @"data source=sharedmssql5.znetindia.net,1234;initial catalog=Database_Name;integrated security=False;user id=user_id;password=san$ec12r214;";


        string strCon = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
        SqlConnection con = new SqlConnection(strCon);
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from ClientDetails where ClientID=@username and Password=@word", con);
            cmd.Parameters.AddWithValue("@username", txtUserID.Text);
            cmd.Parameters.AddWithValue("@word", txtPassword.Text);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            int i = cmd.ExecuteNonQuery();

            if (dt.Rows.Count > 0)
            {
                Response.Cookies["clientid"].Value = txtUserID.Text;  //catch cookies....

                Response.Redirect("/research/recommendations");
            }

            else
            {
                ltrMsg.Text = "Invalid credentials".GetMsgError();
            }
            //con.Close();
        }

        catch (Exception ex)
        {
            ex.ToString();
        }
        finally { con.Close(); }
       
        //using (var ctx = new DAEntities())
        //{
        //    var user = ctx.ClientDetails.FirstOrDefault(a => a.UserID == txtUserID.Text.Trim() && a.Password == txtPassword.Text.Trim());
       
        //    if (user != null)
        //    {
        //        // if (txtUserID.Text == "demo" && txtPassword.Text == "san123")
        //        // {
        //        Response.Cookies["clientid"].Value = txtUserID.Text;
        //        Response.Redirect("/research/san_Default ");
        //    }
        //    else
        //    {
        //        ltrMsg.Text = "Invalid credentials".GetMsgError();
        //    }
        //}

    }
}




Catch Data to other page /after logout

********************** san_Default .cs *******************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class san_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var cId = Request.Cookies["clientid"];
            if (Request.Cookies["clientid"] == null)
            {
                Response.Redirect("/login-reports?redirecturl=/research/recommendations");
            }
        }
    }


    protected void logout(object sender, EventArgs e)
    {
        Response.Cookies.Clear();

        Session.Abandon();
        Response.Cookies["clientid"].Expires = DateTime.Now.AddDays(-1);
        Response.Cookies["clientid"].Expires = DateTime.Now;
        Response.Redirect("/login-reports");
    }

}





Web.config file sample in asp.net / How to write connection string in web.config



<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="resizer" type="ImageResizer.ResizerSection" requirePermission="false" />
  </configSections>
 
    <connectionStrings>
     <add name="DAEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=san-PC;initial catalog=Database_Name;integrated security=False;user id=sa;password=devdba; MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    
     <add connectionString="data source=san-PC;initial catalog=Database_Name;integrated security=False;user id=sa;password=devdba;" name="connectionstring" />
    </connectionStrings>
   
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    <add key="smtp_email" value="online@____.com" />
    <add key="smtp_password" value="_______" />
    <add key="smtp_host" value="smtp.gmail.com" />
    <add key="smtp_port" value="587" />
    <add key="smtp_ssl" value="true" />
    <add key="website_title" value=" :: website name" />
    <add key="is_mail_enable" value="true" />
    <add key="version" value="1.10" />
  </appSettings>
 
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
      <buildProviders>
        <add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider" />
      </buildProviders>
    </compilation>
   
    <machineKey validationKey="078A068393098252DAB62414111EE993A63851F105DFD47984F6FC91290CC04A21346601E310127FB78B7279BB51A587EE85439B397F7B2C04002977A08D48DC" decryptionKey="B395E1984BD2DDE3D08F5FF3DFA60E9B4F04DB50A560AD4C98EC2DC6E773067C" validation="SHA1" decryption="AES" />
    <httpRuntime enableVersionHeader="false" relaxedUrlToFileSystemMapping="true" requestPathInvalidCharacters="" requestValidationMode="4.0" targetFramework="4.5" maxRequestLength="2097151" executionTimeout="36000" />
    <authentication mode="Windows" />
   
    <customErrors mode="Off"></customErrors>
   
    <sessionState customProvider="DefaultSessionProvider" mode="InProc">
      <providers>
        <add connectionStringName="DefaultConnection" name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </providers>
    </sessionState>
   
     <httpCookies httpOnlyCookies="true" requireSSL="false" />
   
     <httpModules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
      </httpModules>
     
      <pages validateRequest="false" enableViewStateMac="false" viewStateEncryptionMode="Never" enableEventValidation="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
       <controls>
        <add tagPrefix="CKEditor" assembly="CKEditor.NET" namespace="CKEditor.NET" />
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
       </controls>
      </pages>
     
  </system.web>
  <system.webServer>
    <httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
      <scheme dll="%Windir%\system32\inetsrv\gzip.dll" name="gzip" />
      <staticTypes>
        <add enabled="true" mimeType="text/*" />
        <add enabled="true" mimeType="message/*" />
        <add enabled="true" mimeType="application/javascript" />
        <add enabled="true" mimeType="application/json" />
        <add enabled="false" mimeType="*/*" />
      </staticTypes>
    </httpCompression>
    <httpErrors errorMode="Custom" existingResponse="PassThrough">
      <remove statusCode="404" subStatusCode="-1" />
      <error path="/notfound" responseMode="ExecuteURL" statusCode="404" subStatusCode="-1" />
      <remove statusCode="500" subStatusCode="-1" />
      <error path="/error" responseMode="ExecuteURL" statusCode="500" subStatusCode="-1" />
    </httpErrors>
   
    <directoryBrowse enabled="false" />
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="false">
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
    </modules>
    <urlCompression doDynamicCompression="true" doStaticCompression="true" />
    <staticContent>
      <clientCache cacheControlMaxAge="30.00:00:00" cacheControlMode="UseMaxAge" />
      <remove fileExtension=".html" />
      <mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
      <remove fileExtension=".css" />
      <mimeMap fileExtension=".css" mimeType="text/css" />
      <remove fileExtension=".js" />
     
    </staticContent>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Content-Type-Options" />
        <add name="X-Content-Type-Options" value="nosniff" />
        <remove name="X-Powered-By" />
        <add name="X-Powered-By" value="My Little Pony" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect newVersion="2.0.0.0" oldVersion="1.0.0.0-2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect newVersion="2.0.0.0" oldVersion="1.0.0.0-2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>