0

I have a text box on my web page for date of birth. I don't want anyone to enter the age less than 16. if someone enters the age less than 16 than I want to show the error message saying "Less than 16 age is not allowed". I want to write this validation on server side rather than client side script. Below is the date of birth field.

<input onblur="selfservice.dateBlurCallback(event)" data-options="{&quot;mode&quot;:&quot;datebox&quot;,&quot;overrideDateFormat&quot;:&quot;%-m/%-d/%Y&quot;,&quot;lockInput&quot;:false,&quot;usePlaceholder&quot;:&quot;mm/dd/yyyy&quot;,&quot;useModal&quot;:false,&quot;overrideSetDateButtonLabel&quot;:&quot;Set Date&quot;,&quot;showInitialValue&quot;:false,&quot;beforeOpenCallback&quot;:&quot;parseDateCallback&quot;}" name="field_RecordingDateID_DOT_StartDate" id="txtDOB" placeholder="mm/dd/yyyy" type="text" data-role="datebox" value="" runat="server"  ></input>

Below is my customvalidator:

<asp:CustomValidator Display="None" ID="CustomValidator1" runat="server" OnServerValidate="ageValidator" ControlToValidate="txtDOB" ErrorMessage=""  />

and below is my server side code:

protected void ageValidator(object source, ServerValidateEventArgs args)
        {
            DateTime dtStart = DateTime.Parse(txtDOB.Value.ToString());
            TimeSpan sp = DateTime.Now - dtStart;

            if (sp.Days < 16 * 365)
            {
                args.IsValid = false;
                CustomValidator1.ErrorMessage = "You have to be at least 16 to order the Certificate";
            }
            else
                args.IsValid = true;
        }

I am not seeing any error message if the date of birth is less than 16. Also, application continues once this method is executed.

any help will be highly appreciated.

Anjali
  • 2,540
  • 7
  • 37
  • 77

1 Answers1

1

You need to include a ValidationSummary control with your asp.net control logic. Even if you populate a property in the CustomValidator control, it makes no sense to just leave it at that point.

Without writing the code entirely out for you, learn about ValidationControls here:

https://www.codeproject.com/articles/20822/custom-validator-and-validation-summary

Here is another excellent example:

https://meeraacademy.com/validationsummary-control-in-asp-net/

Fandango68
  • 4,461
  • 4
  • 39
  • 74