Interpolate value into ErrorMessage in asp:Validator

2022-02-06T10:40:51.893+00:00

A web form "form.aspx" contains an asp:TextBox field "Former_occupation", with a maximum length of 175 characters. The following asp:Validator performs a length check thereon :

<asp:RegularExpressionValidator
ID="CheckOccupationLength"
ControlToValidate="Former_occupation"
runat="server"
ValidationExpression="^[\s\S]{0,175}$"
Text="175 characters max"
ErrorMessage = "'Former Occupation' must be no more than 175 characters"
EnableClientScript="False"
/>

How can I amend it to report the actual number of characters, as in (e.g.,) ""'Former Occupation' must be no more than 175 characters (currently 183)" ? In case relevant, the form starts as follows :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Form.aspx.cs" Inherits="SendMail" ResponseEncoding="utf-8" %>

Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2022-02-06T11:17:06.403+00:00

    No that is not possible with that control. You could always set the MaxLength on the textbox to 175

    https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.textbox.maxlength?view=netframework-4.8


  2. Viorel 122.5K Reputation points
    2022-02-06T13:13:48.167+00:00

    Consider creating a custom server-side validator. Check a simple example:

    public class MyValidator : BaseValidator
    {
        protected override bool EvaluateIsValid( )
        {
            var tb = (TextBox)Page.FindControl( ControlToValidate );
            string text = tb.Text;
    
            if( text.Length <= 10 )
            {
                ErrorMessage = $"The length must be greater than 10. Current length: {text.Length}";
                return false;
            }
            else
            {
                return true;
            }
        }
    }
    

    After compilation it should appear in Toolbox. You can drag it to your form. It will look like this:

    <tag1:MyValidator ID="MyValidator1" runat="server" EnableClientScript="false" ControlToValidate="Former_occupation"/>
    

    Enhance it according to your needs.


  3. Yijing Sun-MSFT 7,096 Reputation points
    2022-02-07T05:21:20.977+00:00

    Hi @Philip Taylor (Hellenic Institute) ,
    I suggest you could use jquery. Just like this:

    171784-screenshot-2022-02-07-132019.png

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.