Home > DeveloperSection > Forums > How to require text in a Textbox?
Allen Scott

Total Post:41

Points:289
Posted on    November-25-2014 9:56 PM

 ASP.Net ASP.NET MVC 
Ratings:


 1 Reply(s)
 606  View(s)
Rate this:

How do I go about requiring text in a textbox? This is what i have so far.

 

String strName = txtName.Text;

String strEmail = txtEmail.Text;

Boolean blnErrors = false;

 

if (strName == null)

{

 

}

else

{

    string script = "alert(\"Name Field Is Required!\");";

    ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);

 

    txtName.Focus();

}

When I run the program and try to execute it, I get the error popping up regardless if I have text entered into the textbox or not. I only want the Error to show if There is Nothing in the TextBox. I have also tried using,

 

if (strName == "")

as well. But nothing changes.



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    November-26-2014 12:12 AM

String strName = txtName.Text.Trim(); //add trim here

String strEmail = txtEmail.Text;

Boolean blnErrors = false;

 

if (string.IsNullOrWhiteSpace(sstrName)) //this function checks for both null or empty string.

{

    string script = "alert(\"Name Field Is Required!\");";

    ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);

    txtName.Focus();

    return;//return from the function as there is an error.

}


Don't want to miss updates? Please click the below button!

Follow MindStick