最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I tell if a text box contains only spaces in c#? - Stack Overflow

programmeradmin0浏览0评论

I have a textbox which is mandatory field and I have wrote a condition.

But User is entering " "(only spaces in textbox). In that scenario my code fails. Can anyone please tell me, how to check textbox contains only spaces in textbox.

if(txtEmployee.Text == ""|| txtEmployee.Text == null || txtEmployee.Text == " ")
{
     this.lblMessage.CssClass = "messageFail";
     this.lblMessage.Text = "Please Enter Request for";
     return;
} 

I have a textbox which is mandatory field and I have wrote a condition.

But User is entering " "(only spaces in textbox). In that scenario my code fails. Can anyone please tell me, how to check textbox contains only spaces in textbox.

if(txtEmployee.Text == ""|| txtEmployee.Text == null || txtEmployee.Text == " ")
{
     this.lblMessage.CssClass = "messageFail";
     this.lblMessage.Text = "Please Enter Request for";
     return;
} 
Share Improve this question edited Sep 18, 2017 at 14:49 Member2017 4312 gold badges8 silver badges16 bronze badges asked Sep 18, 2017 at 14:12 Anil MadhavarapuAnil Madhavarapu 297 bronze badges 7
  • 4 Why not trim it? – epascarello Commented Sep 18, 2017 at 14:12
  • 1 you can use Regex to replace the space with empty string then check it – Niladri Commented Sep 18, 2017 at 14:13
  • 1 Not exactly the same, but: string.IsNullOrWhiteSpace(txtEmployee.Text) – Stefan Commented Sep 18, 2017 at 14:14
  • 3 String.IsNullOrWhiteSpace – Jared Stroebele Commented Sep 18, 2017 at 14:14
  • 1 @Niladri You can. But why make things plicated? – Fildor Commented Sep 18, 2017 at 14:15
 |  Show 2 more ments

3 Answers 3

Reset to default 9

You can use the built-in static method of string IsNullOrWhiteSpace. You can find more info here https://msdn.microsoft./en-us/library/system.string.isnullorwhitespace(v=vs.110).aspx.

So your code should look like this:

if(string.IsNullOrWhiteSpace(txtEmployee.Text))
{
     this.lblMessage.CssClass = "messageFail";
     this.lblMessage.Text = "Please Enter Request for";
     return;
} 

You can use any of these

1. if(!string.IsNullOrEmpty(txtEmployee.Text.Trim()))

2. if(!string.IsNullOrWhiteSpace(txtEmployee.Text))

3. if(txtEmployee.Text.Trim()!=string.Empty)

4. if(txtEmployee.Text.Trim().Length > 0)

Implementation of IsNullorEmpty and IsNullOrWhitespace from reference source

    public static bool IsNullOrEmpty(String value) {
        return (value == null || value.Length == 0);
    }


    public static bool IsNullOrWhiteSpace(String value) {
        if (value == null) return true;

        for(int i = 0; i < value.Length; i++) {
            if(!Char.IsWhiteSpace(value[i])) return false;
        }

        return true;
    }

Check if null or empty & trim

String.Trim String.IsNullOrEmpty

发布评论

评论列表(0)

  1. 暂无评论