0

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;

    }

}

}

  • 1
    Possible duplicate of [Stop postback on TextChanged](http://stackoverflow.com/questions/1524492/stop-postback-on-textchanged) – MethodMan Dec 15 '15 at 20:23
  • @MethodMan : Edited my question – abhishek jaiswal Dec 15 '15 at 20:47
  • http://stackoverflow.com/questions/3915994/asp-net-required-field-validator-for-at-least-one-textbox-contains-text use google for examples.. also since you don't post your .aspx it's going to be hard for anyone to determine where you are making your mistake – MethodMan Dec 15 '15 at 20:53

2 Answers2

0

The page is posting back, so going back to the server and it's kind of fighting with your RequiredFieldValidator. In the background your RequiredFieldValidator is passing Javascript to the page which is then doing its magic and checking to see if it needs to display a message. When a postback event is firing it's posting the whole page back and on it's return it's reloading the page thus losing the jscript message on the UI.

I'd recommend not having the autopostback for something like this as it places unnecessary load onto the server. What exactly do you want that event to do?

Simon Houlton
  • 182
  • 1
  • 10
  • I was just thinking that suppose when I press submit and get something like "Username exists" then even If i change the username the error message will stay there till I press the submit button again.Its like saying that "username exists " on the screen when it actually does not.This will create confusion for a very novice user who is doing things for the first time and especially my target audience. – abhishek jaiswal Dec 15 '15 at 21:42
  • 1
    I'd probably steer clear of informing users when accounts exist, it can be a form of data leakage and could be argued to be less secure if a potential hacker knows half of the credentials required to hack. That aside I'd remove the postback event and let Javascript do the work of the validation. The required field validator should stop a post back of the submit event firing assuming you've correctly wired it. Set autopostback to false (or remove it) and then see if it's working. – Simon Houlton Dec 15 '15 at 21:49
0

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

Khazratbek
  • 1,656
  • 2
  • 10
  • 17