Validating user's input format is not working

Simflex 326 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">
Developer technologies | VB
Developer technologies | ASP.NET | Other
{count} votes

3 answers

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    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 4,811 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


  3. Danny Nguyen (WICLOUD CORPORATION) 725 Reputation points Microsoft External Staff
    2025-07-25T05:29:47.45+00:00

    Hi Simflex,

    Sorry for the late answer. I tried recreating this problem but I found that your code largely works fine (aside from Sub txtdob_TextChanged missing End Sub) and TryParseExact can already handle dates properly. In your case maybe you want to make sure the date doesn't exceed a certain threshold (such as birthday couldn't be later than current date)? then I would just add a check like:

    dateValue > DateTime.Today

    Here's my recreation:

    .aspx:

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="PasswordFormatValidator._Default" %>
     
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Password Format Validator</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    </head>
    <body>
    <form id="form1" runat="server" class="container mt-5">
    <div class="mb-3">
    <label for="txtdob" class="form-label">Enter password (e.g., JD01011900):</label>
    <asp:TextBox ID="txtdob" runat="server" CssClass="form-control" MaxLength="10"
                    Placeholder="First letter of first + last name + MMDDYYYY"
                    AutoPostBack="true" OnTextChanged="txtdob_TextChanged" />
    </div>
    <asp:Label ID="emplabel" runat="server" CssClass="form-text"></asp:Label>
    </form>
    </body>
    </html>
    
    

    aspx.vb:

    Imports System.Text.RegularExpressions
     
    Public Class _Default
        Inherits System.Web.UI.Page
     
        Protected Sub txtdob_TextChanged(sender As Object, e As EventArgs) Handles txtdob.TextChanged
            Dim input As String = txtdob.Text.Trim()
     
            If String.IsNullOrEmpty(input) Then
                emplabel.ForeColor = Drawing.Color.Red
                emplabel.Text = "Empid is required!"
                txtdob.Focus()
                Return
            End If
     
            Dim isValid As Boolean = Validator.ValidateString(input)
     
            If Not isValid Then
                emplabel.ForeColor = Drawing.Color.Red
                emplabel.Text = "Invalid format. Example John Doe, JD02262025"
                txtdob.Focus()
            Else
                emplabel.ForeColor = Drawing.Color.Green
                emplabel.Text = "Valid format!"
            End If
        End Sub
     
        Public Class Validator
            Public Shared Function ValidateString(ByVal input As String) As Boolean
                ' Check format: 2 letters followed by 8 digits
                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
     
                ' Validate date portion (MMDDYYYY)
                Dim datePart As String = input.Substring(2, 8)
                Dim dateValue As DateTime
                If Not DateTime.TryParseExact(datePart, "MMddyyyy", Nothing, Globalization.DateTimeStyles.None, dateValue) Then
                    Return False
                End If
     
                ' Date must not be in the future
                If dateValue > DateTime.Today Then
                    Return False
                End If
     
                Return True
            End Function
     
        End Class
    End Class
    

    Hope I interpreted this correctly. Please tell me if you have any issues.


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.