简体   繁体   中英

Required Field Validator issue validating TextBox value

I have a TextBox which i use to store a url to applied a <asp:HyperLink> control. What i want to do is fire off the RequiredFieldValidator when the TextBox.Text value is empty and the user clicks save . As far as i can tell, my logic is OK, but the validator isn't firing off?

Here's the markup:

<div class="frmRow">
        <div class="frmControls">  
            <asp:Label ID="lblLink" AssociatedControlID="txtImgUrl" runat="server" Text="Image URL"></asp:Label>
            <asp:RequiredFieldValidator ID="imgUrlValidator" runat="server" ControlToValidate="txtImgUrl" ErrorMessage="Enter a Valid URL"  />
            <asp:TextBox ID="txtImgUrl" runat="server" />  
        </div>
        <div class="clearBoth"></div>
    </div>

Here is the code to check a valid absolute URL which is inside my btnSave event:

Uri url;
if (!string.IsNullOrEmpty(txtImgUrl.Text))
{
    txtImgUrl.Text = Uri.TryCreate(txtImgUrl.Text, UriKind.Absolute, out url) ? url.AbsoluteUri : string.Empty;
}

Save button markup:

<br class="clearBoth" />
<asp:Button ID="btnSave" Text="Save Case study" ImageUrl="~/Assets/Design/buttons/btn-update.gif" CssClass="btn fltr" runat="server" OnClick="btnSave_OnClick" />
<div class="clearBoth"></div>

Shouldn't the RequiredFieldValidator be fired off when TryCreate fails on a dodgy URL and txtImgUrl.Text = "" ?

Is there something blatantly obvious that I'm missing here?

Any help is much appreciated

You should check on button click

 if (Page.IsValid) 
         {
            lblOutput.Text = "Required field is filled!";
         }
         else 
         {
            lblOutput.Text = "Required field is empty!";
         }

In ASPX in the button add

CausesValidation="true"

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