问题
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
回答1:
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"
来源:https://stackoverflow.com/questions/11222800/required-field-validator-issue-validating-textbox-value