Rinshad Hameed
Rinshad Hameed

Reputation: 117

How to validate textbox only for spaces?

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

Answers (3)

Amit Singh
Amit Singh

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

StackOverflowUser
StackOverflowUser

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

Edit 1

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

edit 2

Or use string.IsNullOrWhiteSpace

Upvotes: 0

Related Questions