Reputation: 117
I have a tex box in aspx page and i need to validate the text box. How can i do this at server side.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
if(Textbox1.Text=="")
{
lblError.Text ="Enter required field":
}
this is working when user leaves the text box blank. But when he enter white spaces the message is not shown. Is there any solution to this?
Upvotes: 0
Views: 3534
Reputation: 8109
If your using .net 4.0 or above than following work.
if(string.IsNullOrWhiteSpace(Textbox1.Text))
{
lblError.Text ="Enter required field";
}
otherwise you have to check manually...
int flag=0;
char[] c=Textbox1.Text.ToCharArray();
for(int i=0;i<c.length;i++)
{
if(c[i]!=" ")
{
flag=1;
break;
}
}
if(flag==0 || Textbox1.Text==""|| Textbox1.Text==null)
lblError.Text ="Enter required field";
this will check emptiness .null and whitespaces of TextBox
Upvotes: 1
Reputation: 303
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Enter required field" />
try to use required field validator. I think this might help you.
Upvotes: 0
Reputation: 17614
server side
use
trim(textbox1.text)==""
check like this
if(trim(textbox1.text)=="")
//textbox is blank
I you have to check for space in between words then
var words = txtBox.Text.Split(' ');
if(words.Length>0)
// there are spaces in the textbox
Or use string.IsNullOrWhiteSpace
Upvotes: 0