简体   繁体   中英

validate empty value on textbox ASP.NET C#

I have problem about validating empty textbox

My textbox

<asp:TextBox ID="TextBox1" runat="server" MaxLength="50" Width="272px" AutoCompleteType="Disabled">

My label

<asp:Label ID="warning" runat="server" Text="you forgot about this" ForeColor="Red" Visible="false"></asp:Label>

my validation

if (TextBox1.Text == "")
            {
                warning.Visible = true;
            }

it can validate the empty textbox but it can't validate space input

can anybody help me please?

That's because a space isn't "" , so they're not equal.

You can use .IsNullOrWhiteSpace instead:

if (string.IsNullOrWhiteSpace(TextBox1.Text))

This has the added benefit of also checking for null (though in this particular case I don't think .Text would ever be null ) as well as any other purely whitespace characters.

try to use RequiredFieldValidator it validates both client side and server side and also ignore whitespaces during validation. http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.requiredfieldvalidator(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM