Two questions:
On postback when a user clicks submit, how can I add a error message to validation summary?
Is it also possible to highlight a particular textbox using the built in .net validation controls?
Two questions:
On postback when a user clicks submit, how can I add a error message to validation summary?
Is it also possible to highlight a particular textbox using the built in .net validation controls?
Here's a little extension to the good idea from NightOwl888:
Whenever you want to issue an error message, simply call
Page.ErrorMessage
; the mechanism is the same as he suggested.Well all you need to do is create a Custom Validator and add it to the Validator collection of your page, whenever the condition to do so arises.
NOTE: Dont forget to specify the ValidationGroup, or the error message is not going to be displayed inspite of the custom validator being added to your page. And ya, if you do get an answer to your 2nd question(highlighting textbox) do post it!
Add a custom validator and manually set it's
IsValid
andErrorMessage
properties. Sort of like this:In the code behind:
To add error message on validation summary you can use EnableClientScript property of ValidationSummary and the other validation controls. Set EnableClientScript to false all of them :
For highlighting a control, no it's not possible with current controls.
But I put my validation controls near the related controls, and I set their Text property as "*". Then if the validation fails, it appears near failed control.
Maybe you can use custom validator to highlight the failed control. But you should write your own implementation.
Dynamically create a CustomValidator control and add it directly to the Page.Validators collection.
Unlike adding the CustomValidator to the markup, this method allows you to add any number of arbitrary error messages based on server-side business logic.
Note that you can also add it to the page directly, but there are a couple of rules to follow:
You can also create a custom class and implement IValidator, which enables you to add the message with one line of code, but this method doesn't support Validation Groups.
Per Anders Fjeldstad's suggestion, here is a set of handy extension methods.