BladeHal
BladeHal

Reputation: 783

Server side validation for required fields

I am having an issue with the requiredfieldvalidator control not working on an ASP.net page. I have completed the attributes of that field properly, but when I test it, the postback is allowed to happen even if the field in question is blank.

So I want to do server side validation instead. What is the best way to do that? In the event that caused the postback? Also, if I find out the field is blank, how do I get the user back to the screen with all other values they placed on other fields intact and a message saying "This field cannot be blank".

EDIT:

This is the code:

<asp:TextBox ID="fName" TabIndex="1" runat="server" Width="221px" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameRequiredFieldValidator" runat="server"
        ControlToValidate="fName" InitialValue="" ErrorMessage="Filter Name cannot be blank."
        ToolTip="Filter Name cannot be blank.">*</asp:RequiredFieldValidator>

Upvotes: 0

Views: 2348

Answers (4)

Tomasz
Tomasz

Reputation: 38

Try to remove the CauseValidation property from TextBox and InvalidValue from validator default values just works just fine.

Server side validation is run after Page_Load and controls events. If you are using the required validator you don't need to write any extra code.

In Button_Click event just check this.Page.IsValid flag.

Upvotes: 2

Chains
Chains

Reputation: 13167

Remove InitialValue="" 

Only reason to use that on a textbox is if you have some default text in there (like "Enter a value", or some such).

Upvotes: 0

Brandon leach
Brandon leach

Reputation: 130

Can you post the html part of the code relating to the validator and the text box to validate. Off the bat it sounds like your missing the ControlToValidate property of the validator. You can also use the IsValid property of the page class to test wether page validation passed.

This works fully functional.

<asp:TextBox ID="TextBox1" runat="server" />;

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="*" />

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Upvotes: 0

Erix
Erix

Reputation: 7105

First off, post the code for your requiredfieldvalidator, because you're clearly doing something incorrectly.

However, it's good to check on both client and server side, so I'll answer your other question.

I usually check for validity in the event handler of the postback. You can set the values of a Label there to indicate the failure. Values in all fields should remain as they were entered since this is a postback.

Upvotes: 0

Related Questions