Search code examples
c#asp.netcode-behinddynamically-generatedrangevalidator

How to put HTML elements inside a RangeValidator control programmatically in ASP.NET?


If I wanted to create the RangeValidator statically from my *.aspx, it would go like this:

<asp:RangeValidator Type="Double" MinimumValue="0.00" MaximumValue="100.00" 
ID="rangeValidatorSomething" ControlToValidate="textBoxSomething" runat="server" 
Display="Dynamic" >
    <img src="../images/error.gif" alt="Validation error" title="Validation error" />
    This number should be between 0.00 and 100.00
</asp:RangeValidator>

I want to create the same RangeValidator control programmatically, because I want to allow the user to choose the amount of data that he/she wants to provide (meaning the number of TextBox controls). Therefore, I need to make sure that the data in the newly created TextBox controls is valid. That's why I want to create a RangeValidator from the code-behind like this:

RangeValidator dynamicRangeValidator = new RangeValidator();
dynamicRangeValidator.MinimumValue = "0.00";
dynamicRangeValidator.MaximumValue = "100.00";
dynamicRangeValidator.Type = ValidationDataType.Double;
...

My question is: how should I implement the image and the text that is supposed to be inside the RangeValidator control, like shown in the *.aspx example above?


Solution

  • See below sample for the required field validator :

    <asp:TextBox runat="server" ID="textValue"></asp:TextBox>
     <asp:RequiredFieldValidator runat="server" Text='<img src="error.png" />' ControlToValidate="textValue"></asp:RequiredFieldValidator>