B4J Code Snippet Password validation using RegEx

B4X:
'Tests given password against the given rules
Public Sub IsValidPassword(PasswordToValidate As String, HasAtLeastOneLetter As Boolean, HasAtLeastOneNumber As Boolean, HasAtLeastOneCapital As Boolean, HasAtLeastOneSpecialChar As Boolean, MinLength As Int, MaxLength As Int) As Boolean
    If PasswordToValidate.Length = 0 Then Return False
    If Not(HasAtLeastOneLetter) And Not(HasAtLeastOneNumber) And Not(HasAtLeastOneCapital) And Not(HasAtLeastOneSpecialChar) And MinLength = 0 And MaxLength = 0 Then Return True
    Dim regexPattern As StringBuilder : regexPattern.Initialize
    regexPattern.Append("^")
    If HasAtLeastOneLetter Then regexPattern.Append("(?=.*[a-z])")
    If HasAtLeastOneNumber Then regexPattern.Append("(?=.*[0-9])")
    If HasAtLeastOneCapital Then regexPattern.Append("(?=.*[A-Z])")
    If HasAtLeastOneSpecialChar Then regexPattern.Append("(?=.*[~!@#$%^&+=])")
    regexPattern.Append("(?!.*\s)") 'no white spaces or tabs
    If MinLength > 0 Or MaxLength > 0 Then
        regexPattern.Append(".{")
        regexPattern.Append(MinLength & ",")
        If MaxLength > 0 Then
            regexPattern.Append(MaxLength & "}")
        Else
            regexPattern.Append("}")
        End If   
    End If
    regexPattern.Append("$")
    Return Regex.IsMatch(regexPattern.ToString, PasswordToValidate)
End Sub
 
Top