Validating user's input format is not working

Simflex 301 Reputation points
2025-02-18T23:08:28.06+00:00

Our requirement is to ask users to create a password with the following format:

First letter of firstname+First letter of lastname+2 digits of month+2 digits of day+4 digits of year.

For instance, a user with the name of John Doe, born January 1, 1900 will have the format of JD01011900.

Any input not in this format generates an error to the user letting him/her know input is invalid...

The following code is not working in the sense that when I intentionally enter wrong date format like JD01012300, we expect an error message shown to the user that the input format is incorrect,

However, no error is getting displayed.

Instead, whatever input the user entered goes through as valid.

Can someone please help with why this is not working?

Entire code is below:

Imports System
Imports System.Text.RegularExpressions

    Protected Sub txtdob_TextChanged(sender As Object, e As EventArgs) Handles txtdob.TextChanged

        Dim input As String = txtdob.Text

        Dim isValid As Boolean = Validator.ValidateString(input)

        If String.IsNullOrEmpty(txtdob.Text.Trim()) Then

              emplabel.ForeColor = System.Drawing.Color.Red

            emplabel.Text = "Empid is required!"

            Me.txtdob.Focus()

        ElseIf Not isValid Then

            emplabel.ForeColor = System.Drawing.Color.Red

            emplabel.Text = "Invalid format. Example John Doe, JD02262025"

            Me.txtdob.Focus()

        End If

        

    Public Class Validator

        Public Shared Function ValidateString(ByVal input As String) As Boolean

            If input.Length <> 10 Then Return False

            Dim pattern As String = "^[A-Za-z]{2}\d{8}$"

            If Not Regex.IsMatch(input, pattern) Then Return False

            Dim datePart As String = input.Substring(2, 8)

            Dim dateValue As DateTime

            If Not DateTime.TryParseExact(datePart, "MMddyyyy", Nothing, System.Globalization.DateTimeStyles.None, dateValue) Then

                Return False

            End If

            Return True

        End Function

    End Class

    

    HTML:

    <asp:TextBox ID="txtdob" maxlength="10" placeholder="Enter Combination..." Style="width: 250px;" class="form-control"

    runat="server" AutoPostBack="true" OnTextChanged="txtdob_TextChanged">
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,598 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,783 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jiachen Li-MSFT 33,536 Reputation points Microsoft Vendor
    2025-02-19T01:34:26.5733333+00:00

    Hi @Simflex ,

    Uses DateTime.TryParseExact with "dd/MM/yyyy" to check if the date is valid (e.g., rejects 31/04/2024 or 29/02/2025 as 2025 is not a leap year).

        Function IsValidInput(ByVal input As String) As Boolean
            Dim pattern As String = "^[A-Z]{2}(\d{2})(\d{2})(\d{4})$"
            Dim match As Match = Regex.Match(input, pattern)
    
            If match.Success Then
                Dim day As Integer = Integer.Parse(match.Groups(1).Value)
                Dim month As Integer = Integer.Parse(match.Groups(2).Value)
                Dim year As Integer = Integer.Parse(match.Groups(3).Value)
    
                ' Validate the date
                Dim dateString As String = $"{day:D2}/{month:D2}/{year:D4}"
                Dim parsedDate As DateTime
    
                If DateTime.TryParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, parsedDate) Then
                    Return True
                End If
            End If
    
            Return False
        End Function
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 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.


  2. SurferOnWww 3,796 Reputation points
    2025-02-19T13:01:57.32+00:00

    I understand that your app is the ASP.NET Web Forms. If so, I suggest that you use the RequiredFieldValidator, RegularExpressionValidator and CustomValidator as follows:

    .aspx.cs

    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebForms1
    {
    	public partial class WebForm55 : System.Web.UI.Page
    	{
    		protected void Page_Load(object sender, EventArgs e)
    		{
    
    		}        
    
            protected void CustomValidator1_ServerValidate(object source, 
                                            ServerValidateEventArgs args)
            {
                var datePart = args.Value.Substring(2, 8);
                DateTime dateValue;
                if (DateTime.TryParseExact(datePart, "MMddyyyy", null, 
                        System.Globalization.DateTimeStyles.None, 
                        out dateValue))
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                if (Page.IsValid)
                {
                    // do something
                }
            }
        }
    }
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true"
        CodeBehind="WebForm55.aspx.cs"
        Inherits="WebForms1.WebForm55" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            .style1 {
                display: none;
            }
        </style>
        <script type="text/javascript">
            // AutoPostBack of TextBox does not work properly with the
            // validators. Button must be clicked to postback. The following
            // script click the hidden Button at the change event of TextBox.
            let textBox, btn;
            window.addEventListener('DOMContentLoaded', () => {
                textBox = document.getElementById('<%=txtdod.ClientID%>');
                btn = document.getElementById('<%=Button1.ClientID%>');
                textBox.addEventListener("change", () => {
                    btn.click();
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:TextBox
                ID="txtdod"
                MaxLength="10"
                placeholder="Enter Combination..."
                Style="width: 250px;"
                runat="server">
            </asp:TextBox>
    
            <asp:RequiredFieldValidator
                ID="RequiredFieldValidator1"
                runat="server"
                ErrorMessage="Empid is required!"
                ControlToValidate="txtdod"
                Display="Dynamic"
                ForeColor="Red">
            </asp:RequiredFieldValidator>
    
            <asp:RegularExpressionValidator
                ID="RegularExpressionValidator1"
                runat="server"
                ErrorMessage="Invalid format. Example John Doe, JD02262025"
                ControlToValidate="txtdod"
                Display="Dynamic"
                ValidationExpression="^[A-Za-z]{2}\d{8}$"
                ForeColor="Red">
            </asp:RegularExpressionValidator>
    
            <asp:CustomValidator ID="CustomValidator1"
                runat="server"
                ErrorMessage="Invalid date"
                Display="Dynamic"
                ControlToValidate="txtdod"
                OnServerValidate="CustomValidator1_ServerValidate"
                ForeColor="Red">
            </asp:CustomValidator>
            <br />
    
            <%--hidden button--%>
            <asp:Button ID="Button1"
                runat="server"
                Text="Button"
                OnClick="Button1_Click" 
                CssClass="style1" />
        </form>
    </body>
    </html>
    

    Result of validation by CustomValidator:

    enter image description here


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.