Search code examples
c#asp.netrequiredfieldvalidatorautopostback

AutoPostBack and RequiredFieldValidator behaviour


I have a username text box with AutoPostBack property and RequiredFieldValidator.The problem is when I type something in the text box then come out of it thus triggering AutoPostBack now if I come back to the text box and delete what I have typed and then come out of textbox the form displays the message "Username is required" but its just flashes for a second and then the page refreshes .
I don't understand this behaviour . Can I somehow change the form so that either the "Username is required" message stays or it doesnt flash at all. And if I come out of the text box without typing nothing happens (not even AutoPostBack I think)
The other problem is same but I think my doubts are a bit different:
Why is RequiredFieldValidator not fired if the text box is empty and I press tab or what actually triggers RequiredFieldValidator
If RequiredFieldValidator is invalid why does AutoPostBackstill occur,is not Validators checked before in page life cycle?

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

namespace Registration_LoginPortel
{
public partial class RegistrationPage : System.Web.UI.Page
{
    int i = 0;
    protected void Page_Load(object sender, EventArgs e)
    {



    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        lblLoginAvailable.Visible = false;
        Response.Write("PPpostback" + (++i));
        if (!CheckLogin(Usn.Text.ToString().Trim()))
        {
            //Register the user
            try
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
                con.Open(); string s = Usn.Text;
                string sql_insertQuery = "INSERT INTO UserData(username,password,country)values (@UName,@UPass,@UCountry)";
                //string sql_insertQuery = "INSERT into UserData(username,password,country) VALUES ('"+Usn.Text+"','"+pass.Text+"','"+country.Text+"')";
                SqlCommand com = new SqlCommand(sql_insertQuery, con);
                com.Parameters.AddWithValue("@UName", Usn.Text);
                com.Parameters.AddWithValue("@UPass", pass.Text);
                com.Parameters.AddWithValue("@UCountry", country.Text);

                com.ExecuteNonQuery();
                // Response.Redirect("Admin.aspx");
                Response.Write("Registration is successfull");
                con.Close();
            }
            catch (Exception ex)
            {
                //Response.Write("Error : " + ex.Message);
                Response.Write("\n\nError : " + ex.ToString());
            }
        }
        else
        {
            lblLoginAvailable.Visible = true;
            lblLoginAvailable.Text = "This login already exists in our system. Chooce another login please";
        }
    }
    protected bool CheckLogin(string login)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select count(*) from UserData where lower(username) = lower(@login)", con);
        cmd.Parameters.Add("@login", SqlDbType.VarChar).Value = login;
        string id = "";
        try
        {
            con.Open();
            id = (int)cmd.ExecuteScalar() == 0 ? "" : cmd.ExecuteScalar().ToString();
        }
        catch (Exception ex)
        {
            //...
        }
        finally
        {
            con.Close();
        }
        if (String.IsNullOrEmpty(id)) return false;
        return true;
    }


    protected void Usn_TextChanged(object sender, EventArgs e)
    {
        lblLoginAvailable.Visible = false;

    }

}

}


Solution

  • you may just delete your requiredfieldvalidator, and your button's code will be:

    <asp:Button ID="btnSubmit" runat="server" OnClientClick="return checkvalue();" OnClick="Button_Click" />
    

    checkvalue() is an javascript method, using which you will check your textbox's value.

    <script type="text/javascript">
        function checkvalue(){
            var txt = document.getElementById("yourTextboxId");
            if (txt.value.length == 0){
                alert('Insert a data');
                txt.focus();
                return false;
            }
            return true;
        }
    </script>
    

    This script will occur only when user will click on the button, it will not fire a postback. This script will check length of text inside your textbox and, if length is 0 which means no text is inputted, will ask an user to input the text and cursor will be automatically set to your textbox control.

    Hope it helps