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
3 Answers
Reset to default 9You 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