String Date validation return incorrect validation

I have date coming in string in format 28042022 DDMMYYYY which I then convert to 28/04/2022 using following code

public static string MultiInsert(this string str, string insertChar, params int[] positions)
{
    StringBuilder sb = new StringBuilder(str.Length + (positions.Length * insertChar.Length));
    var posLookup = new HashSet<int>(positions);
    for (int i = 0; i < str.Length; i++)
    {
        sb.Append(str[i]);
        if (posLookup.Contains(i))
            sb.Append(insertChar);

    }
    return sb.ToString();

}

up to this point is all good but then following code don’t return me correct bool for validation

public override ValidationStatus Validate(string Text)
{
    ValidationStatus validationStatus = new ValidationStatus();

    if (!string.IsNullOrEmpty(Text))
    {
        int[] index = { 1, 3 };

        var date = StringExtensions.MultiInsert(Text, "/", index);

        DateTime tempDate;

        var isDateValid = DateTime.TryParseExact(date, "dd/MM/YYYY", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDate);

    }

    return validationStatus;
}

>Solution :

You use incorrect format (for years).

Change this:

"dd/MM/YYYY"

to this:

"dd/MM/yyyy" // lowercase Y

Leave a Reply