Home About Us SQL Interview Book Contact Us RSS
Articles
Tools
Code Snippets
Links
Tips & Tricks
FAQ
Resources
Articles
Code Snippets
Links
FAQ
Resources

Saravana Kumar
Vinod Kumar


Displaying Custom Message in Validation Summary 

Most of us would have come across a situation where we need to display a custom message other than the error message from validators in the validation summary. For example, based on business logic check you need to display a message to the user. Already you have a validation summary in the page where you are displaying error message to the user, you might prefer to add your message to that validation summary. There are multiple ways to achieve this, here I am going to explain one of the ways to display custom message in validation summary.  

Validation Summary does not allows you to add a custom message. However, it has a property “HeaderText” using which you can specify a header text to the validation summary. 

validationSummaryCtrl.HeaderText = @"Header Text";  

Using this property, you can also specify a custom message along with header text. However, you should use this option only if you want to display a message permanently i.e. whenever validation fails in the page, validation summary will appear along with your custom text. 

Most of the times we wont have requirement like this, you want to display custom message only during certain time. In those case, you cant use this option. Simpler way to display a custom message in the validation summary is using custom validator, just place a custom validator in the page or dynamically add a custom validator to the page and specify your message in ErrorMessage property of the custom validator control and change its IsValid property to false. Validation Summary control will pick up your message from custom validator as its Valid status is false. For example, to add custom message to validation summary in your page, just call this method with your custom message.

private void DisplayCustomMessageInValidationSummary(string message)

      {

            CustomValidator CustomValidatorCtrl = new CustomValidator();

            CustomValidatorCtrl.IsValid = false;

            CustomValidatorCtrl.ErrorMessage = message;

            this.Page.Controls.Add(CustomValidatorCtrl);

      }  

Note : To add a line break in your custom message, just add <br> html tag to your error message. If you try with other ways, it will not work. Even, if you have System.Enviornment.NewLine in your message string, validation Summary wont take this line breaks, it will display in single line only. However, if you add <br> tag, validation summary doesn’t remove this from your error message and hence your message will display in two lines.