Password validation REGEX to disallow whitespaces

前端 未结 3 1505
日久生厌
日久生厌 2020-12-12 02:23
  • Password cannot contain white spaces
  • must contain at least one numeric char
  • must contain 1 capital letter
  • and be at least 8 characters in le
相关标签:
3条回答
  • 2020-12-12 03:10

    ^((?!.*[\s])(?=.*[A-Z])(?=.*\d).{8,15})

    0 讨论(0)
  • 2020-12-12 03:10

    Just match:

    ^(?!.* )(?=.*\d)(?=.*[A-Z]).{8,15}$
    

    How it works:

    .{8,15} means: 8 to 15 characters

    (?!.* ) means: does not contain " "
    (?=.*\d) means: contains at least one digit.
    (?=.*[A-Z]) means: contains at least one capital letter

    0 讨论(0)
  • 2020-12-12 03:22

    As an alternative to RegEx, have you considered just basic string parsing? In other words, if you're needing assistance to write the RegEx, what will happen with the maintainability over time?

    Simple string parsing is much easier to understand for most of us. Those that follow in our footsteps will have a much easier time understanding the code and adding other requirements as well.

    Here's an example using string parsing that is self-documenting, even without the error messages.

    /// <summary>
    /// Determines whether a password is valid.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <returns>A Tuple where Item1 is a boolean (true == valid password; false otherwise).
    /// And Item2 is the message validating the password.</returns>
    public Tuple<bool, string> IsValidPassword( string password )
    {
        if( password.Contains( " " ) )
        {
            return new Tuple<bool, string>( false, "Password cannot contain white spaces." );
        }
    
        if( !password.Any( char.IsNumber ) )
        {
            return new Tuple<bool, string>( false, "Password must contain at least one numeric char." );
        }
    
        // perhaps the requirements meant to be 1 or more capital letters?
        // if( !password.Any( char.IsUpper ) )
        if( password.Count( char.IsUpper ) != 1 )
        {
            return new Tuple<bool, string>( false, "Password must contain only 1 capital letter." );
        }
    
        if( password.Length < 8 )
        {
            return new Tuple<bool, string>( false, "Password is too short; must be at least 8 characters (15 max)." );
        }
    
        if( password.Length > 15 )
        {
            return new Tuple<bool, string>( false, "Password is too long; must be no more than 15 characters (8 min)." );
        }
    
        return new Tuple<bool, string>( true, "Password is valid." );
    }
    
    0 讨论(0)
提交回复
热议问题