anass 90 anass 90 - 9 days ago 11
HTML Question

password verification non successive numbers with javascript

I need to verify the password entered with this criteria with JavaScript (server-side c# would be great if possible) with showing messages:-


  • password needs to be numeric.

  • length <= 8.



and this is where the complexity stand :-


  • I can't have like 11111111 or 22222222 or 55559852 or 12349421 or 98762534 from both sides



so I need to control the succession of the numbers for 4 digits wherever they are located. Any help will be appreciated. Thank You.

Answer

Try using this algoritm:

Javascript Code:

https://jsfiddle.net/b8xm4zkg/1/

function validatePassword(password)
{
    if(isNaN(password))
        return false;

    if(password == null || password.length < 7)
        return false;

    for(var x = 3; x <= password.length; x++)
    {
        if(password[x] == password[x-1] && password[x] == password[x-2] && password[x] == password[x-3])
            return false;

        var pNumber = parseInt(password[x]);

        if(pNumber + 1 == password[x-1] && pNumber + 2 == password[x-2] && pNumber + 3 == password[x-3])
            return false;

        if(pNumber - 1 == password[x-1] && pNumber - 2 == password[x-2] && pNumber - 3 == password[x-3])
            return false;
    }

    return true;
}

JS Usage:

if(validatePassword("1233457638789"))
{
    //Valid
}
else
{
    //Invalid
}

C# Code:

https://dotnetfiddle.net/Mf4aLB

public static bool ValidatePassword(string password)
{
    if (string.IsNullOrWhiteSpace(password))
        return false;

    if(password.Length <= 7)
        return false;

    string justNumbers = new String(password.Where(Char.IsDigit).ToArray());
    if(!justNumbers.Equals(password))
       return false;

    for(int x = 3; x < password.Length; x++)
    {
        if(password[x] == password[x-1] && password[x] == password[x-2] && password[x] == password[x-3])
            return false;

        int pNumber = int.Parse(password[x].ToString()); 

        if ((pNumber + 1).ToString() == password[x-1].ToString() && (pNumber + 2).ToString() == password[x-2].ToString() && (pNumber + 3).ToString() == password[x-3].ToString())
            return false;

        if ((pNumber - 1).ToString() == password[x-1].ToString() && (pNumber - 2).ToString() == password[x-2].ToString() && (pNumber - 3).ToString() == password[x-3].ToString())
            return false;
    }

    return true;
}

C# Usage:

if(ValidatePassword("1233457638789"))
{
    //Valid
}
else
{
    //Invalid
}
Comments