Created
November 26, 2024 15:33
-
-
Save Asheshp23/b39922cb2bfdb9efbe53d4793820c4ad to your computer and use it in GitHub Desktop.
SwiftUI ContentView with Password Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ContentView: View { | |
@State private var password: String = "" | |
@State private var isPasswordValid: Bool = true | |
@State private var passwordValidationMessage: String = "" | |
var body: some View { | |
VStack(spacing: 20) { | |
SecureField("Enter Password", text: $password) | |
.padding() | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
if !isPasswordValid { | |
Text(passwordValidationMessage) | |
.foregroundColor(.red) | |
.padding(.top, 5) | |
} | |
Button("Submit") { | |
if validatePassword(password) { | |
print("Password is valid") | |
isPasswordValid = true | |
} else { | |
isPasswordValid = false | |
print("\(passwordValidationMessage)") | |
} | |
} | |
.padding() | |
.background(isPasswordValid ? Color.blue : Color.gray) | |
.foregroundColor(.white) | |
.cornerRadius(10) | |
} | |
.padding() | |
} | |
@MainActor | |
func validatePassword(_ password: String) -> Bool { | |
var validationMessages: [String] = [] | |
// Validate password length | |
if password.count < 6 { | |
validationMessages.append("Password must be at least 6 characters long.") | |
} | |
// Validate uppercase letter | |
if !password.contains(where: { $0.isUppercase }) { | |
validationMessages.append("Password must contain at least one uppercase letter.") | |
} | |
// Validate lowercase letter | |
if !password.contains(where: { $0.isLowercase }) { | |
validationMessages.append("Password must contain at least one lowercase letter.") | |
} | |
// Validate digit | |
if !password.contains(where: { $0.isNumber }) { | |
validationMessages.append("Password must contain at least one number.") | |
} | |
// Validate special character | |
let specialCharacterSet = "!@#$%^&*()_+=-[]{}|;:'\",.<>?/~" | |
if !password.contains(where: { specialCharacterSet.contains($0) }) { | |
validationMessages.append("Password must contain at least one special character.") | |
} | |
// If there are validation messages, set the validation feedback and return false | |
if !validationMessages.isEmpty { | |
passwordValidationMessage = validationMessages.joined(separator: "\n") | |
return false | |
} | |
return true | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment