How do I change what the RequiredFieldValidator control returns?
I'm pretty new to ASP.NET, but I am trying to validate a form. I've got the validation working, but I want to change how it displays. I'm using the RequiredFieldValidator control which generates a span tag with the ErrorMessage attribute inside. Depending on how I set some of the attributes, the span tag is either hidden or displayed with inline CSS (display:none, visibility:hidden, etc). Rather than have the validation return a span, I'd like to have the CssCl开发者_C百科ass of the TextBox control change based on the result of the validation. I don't want a validation related span anywhere in my markup, even with display:none.
Is this possible? Where do I start to achieve this?
Thanks!
You cannot change the RequiredFieldValidator to update another control like a text box, it will only update itself or a ValidationSummary if there is one on the page.
2 options you have to get your desired output are:
- Use a CustomValidator control
- Create your own validation server control that is capable of updating the css class of a textbox
While most likely neither of these options will give you the "pure" HTML code you are looking for without any extra span or div tags, they will meet your other requirements provided you are willing to put in the time to write the JavaScript (or jQuery). However, considering the alternatives that are available (mostly client-side only validation via some framework), you are still better off sticking with ASP.NET validation because it can enforce the validation on the server side.
The second option is more challenging, but a server control can be used on any page in your project or wrapped in a DLL to be deployed in multiple projects. With a CustomValidator there is some copy and paste if you want to duplicate the functionality on multiple controls, which can get difficult to maintain.
For a real-world example of how you can use jQuery and custom server controls to get the results you are looking for, go to the checkout page on Folding Chair Depot (you will need to add an item to the cart first to get there). When you submit the form without filling it out, the invalid textboxes are assigned new css classes which change their background color. However, because they are server controls, the functionality will work whether JavaScript is enabled or not.
It is more work, but it is possible with CustomValidator. So you have more control through the validation js function.
精彩评论