C# - Validate MD5

By , 1/2/2016
(0 ratings)
This method validates a MD5 hash string. It does not use any Regex to do the job, only easy build-in features of .NET.

I published two versions, one in C#6 syntax with LINQ and another one in the classic syntax.

Required Namespaces - for C# 6 Version
System.Linq

Translate to VB
//C# 6 syntax with LINQ

/// <summary>
/// Validates a MD5 hash string.
/// </summary>
/// <param name="md5">The string to test.</param>
/// <returns><c>true</c>, in case <paramref name="md5"/> is valid; otherwise <c>false</c>.</returns>
static bool IsValidMD5(string md5) => md5 != null && md5.Length == 32 && md5.All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F'));

//old C# syntax

/// <summary>
/// Validates a MD5 hash string.
/// </summary>
/// <param name="md5">The string to test.</param>
/// <returns><c>true</c>, in case <paramref name="md5"/> is valid; otherwise <c>false</c>.</returns>
static bool IsValidMD5(string md5)
{
    if (md5 == null || md5.Length != 32) return false;
    foreach (var x in md5)
    {
        if ((x < '0' || x > '9') && (x < 'a' || x > 'f') && (x < 'A' || x > 'F'))
        {
            return false;
        }
    }
    return true;
}
Tagged with MD5, Validator, Validate, LINQ.

Comments

 

Log in, to comment!