58

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?

TStamper
  • 30,098
  • 10
  • 66
  • 73
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

6 Answers6

90

Dynamically create a CustomValidator control and add it directly to the Page.Validators collection.

Dim err As New CustomValidator
err.ValidationGroup = "MyGroup"
err.IsValid = False
err.ErrorMessage = "The password is invalid"
Page.Validators.Add(err)

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:

  1. You must add the control to the same naming container as the controls of the validation group.
  2. If you don't want the validation message to appear in a random position in the page, you will either have to add the validator to a specific container or you will need to supress it using a CSS class or style.

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 are a set of handy extension methods.

Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices

Public Module PageExtensions

    <Extension()> _
    Public Sub AddValidationError(ByVal p As System.Web.UI.Page, ByVal errorMessage As String)
        p.AddValidationError(errorMessage, String.Empty)
    End Sub

    <Extension()> _
    Public Sub AddValidationError(ByVal p As System.Web.UI.Page, ByVal errorMessage As String, ByVal validationGroup As String)
        Dim err As New CustomValidator
        err.ValidationGroup = validationGroup
        err.ErrorMessage = errorMessage
        err.IsValid = False
        p.Validators.Add(err)
    End Sub

End Module
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • 4
    +1 for enabling arbitrary number of error messages. Plus, the above code could easily be factored out into an extension method to either System.Web.UI.Page or System.Web.UI.ValidatorCollection, which would enable reuse through something like Page.AddValiationError("MyValidationGroup", "Some error message") – Anders Fjeldstad Jun 30 '11 at 13:52
  • I found that once I'd added the validators this way (and added them to a control on the page, so I could control where they appeared), if I didn't set the `ControlToValidate` property then I couldn't change the thing that was making the page invalid - so I couldn't ever submit the page again. Setting that property fixed it for me. – Ian Grainger Sep 25 '15 at 09:19
  • Very useful @NightOwl888. Just for conveniaice the same code but in C# `CustomValidator err = new CustomValidator(); err.ValidationGroup = "MyGroup"; err.IsValid = false; err.ErrorMessage = "The Password is Invalid"; Page.Validators.Add(err);` – apereira Dec 03 '15 at 15:18
  • I would suggest to take into consideration the ValidationGrouo property. This could be an extension method to ValidationSummary without the need to pass the page – Marco Alves Jul 14 '17 at 03:29
  • This helped me considerably and was easy to understand,. thanks – David Sep 21 '21 at 19:59
49

Add a custom validator and manually set it's IsValid and ErrorMessage properties. Sort of like this:

<asp:panel ID="ErrorsPanel" runat="server" CssClass="ErrorSummary">
    <asp:CustomValidator id="CustomValidator1" runat="server" 
        Display="None" EnableClientScript="False"></asp:CustomValidator>
    <asp:ValidationSummary id="ErrorSummary" runat="server" 
        HeaderText="Errors occurred:"></asp:ValidationSummary>
</asp:panel>

In the code behind:

//
// Update the database with the changes
//
string ErrorDetails;
if (!Db.Update(out ErrorDetails))
{
    CustomValidator1.IsValid = false;
    CustomValidator1.ErrorMessage = ErrorDetails;
}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
user53794
  • 3,800
  • 2
  • 30
  • 31
  • 6
    One trap here is that if your validation summary control specifies a ValidationGroup, then you also need to add a ValidationGroup attribute to your CustomValidator to ensure the error message is displayed when/where required. Maybe just commonsense but it's caught me out occasionally. – David Clarke Oct 28 '10 at 20:52
7

Here's a little extension to the good idea from NightOwl888:

public class ValidationError : CustomValidator
{
    public ValidationError(string group, string msg)
        : base()
    {
        base.ValidationGroup = group;
        base.ErrorMessage = msg;
        base.IsValid = false;
    }
}

public static class PageExtensions
{
    public static void ErrorMessage(this Page page, string group, string msg)
    {
        page.Validators.Add(new ValidationError(group, msg));
    }
}

Whenever you want to issue an error message, simply call Page.ErrorMessage; the mechanism is the same as he suggested.

atlaste
  • 30,418
  • 3
  • 57
  • 87
  • Maybe make the `group` optional so if the ValidationSummary doesn't define one the ValidationError will still work with it. – Daniel Ballinger Jan 08 '14 at 23:40
  • @DanielBallinger Sure...? Note that my code examples are not intended to be production code, just to illustrate things can be implemented - after all, I'm not here to do the work of other people as a charity service... – atlaste Jan 09 '14 at 09:11
  • 1
    Sorry, I should have been clearer. I didn't intend for you to update the example or anything. More as a note for others to consider when actually implementing it. Hopefully save them a few minutes of effort. – Daniel Ballinger Jan 09 '14 at 18:20
6

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.

CustomValidator cv = new CustomValidator();

if(condition)
{
cv.IsValid = false;
cv.ErrorMessage = "This Catalog Data already exists.";
cv.ValidationGroup = "InputList";
this.Page.Validators.Add(cv);
}

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!

Sayan
  • 2,053
  • 3
  • 25
  • 36
3

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 :

<asp:ValidationSummary
HeaderText="You must enter a value in the following fields :"
DisplayMode="BulletList"
EnableClientScript="false"
runat="server"/>

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.

Canavar
  • 47,715
  • 17
  • 91
  • 122
0

Here is a version of the above answers that is an extension method for ValidationSummary, which takes care of the validation group ID.

public static void AddCustomMessage(this ValidationSummary summaryControl, string message)
{
    summaryControl.Page.Validators.Add(new CustomValidator {
        ValidationGroup = summaryControl.ValidationGroup,
        ErrorMessage = message,
        IsValid = false
    });
}

dgasaway
  • 66
  • 6