我在生成错误文本时遇到问题。
@State private var email = ""
@State private var password = "Vignesh123!"
private func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
private func isPasswordValid(_ password : String) -> Bool{
let passwordFormat = "^(?=.*[A-Z])(?=.*[a-z])(?=.*?[0-9])(?=.*[$@$#!%*?&])[A-Za-z\d$@$#!%*?&]{8,}"
let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordFormat)
return passwordTest.evaluate(with: password)
}
private func validView() -> String? {
if !self.isValidEmail(email) {
return "Email is invalid"
}
if !self.isPasswordValid(password) {
return "Password is invalid"
}
// Do same like other validation as per needed
return nil
}
在我编写的代码中,我使用TextField显示密码。
VStack(spacing: 0) {
Spacer()
VStack(alignment: .leading) {
TextField("Email", text: $email)
.textFieldStyle(DefaultTextFieldStyle())
.padding(.leading)
.frame(height: 50)
.background(.gray.opacity(0.3))
.cornerRadius(10)
.autocapitalization(.none)
if password.isEmpty {
Text("Email is Not Valid")
.font(.footnote).foregroundColor(.red).hidden()
} else if (self.validView() != nil) {
Text("Email is Not Valid")
.font(.footnote).foregroundColor(.red)
.padding(3)
}
}
VStack(alignment: .leading) {
TextField("Password", text: $password)
.textFieldStyle(DefaultTextFieldStyle())
.padding(.leading)
.frame(height: 50)
.background(.gray.opacity(0.3))
.cornerRadius(10)
.autocapitalization(.none)
if password.isEmpty {
Text("Password is Not Valid")
.font(.footnote).foregroundColor(.red).hidden()
} else if (self.validView() != nil) {
Text("Password is Not Valid")
.font(.footnote).foregroundColor(.red)
.padding(3)
}
}
Button(action: {
// Show error message here
if let errorMessage = self.validView() {
print(errorMessage)
return
}
}, label: {
Text("Login")
.frame(height: 45).frame(maxWidth: .infinity)
.background(.blue)
.foregroundColor(.white)
.cornerRadius(10)
})
Spacer()
}.padding()
结果应该是当我输入不合适的电子邮件/密码并单击Login
时,应该出现错误文本。以上代码是我的尝试👆
我可能犯了一些基本的错误,我希望你能正确理解。感谢大家的关注,谢谢大家。为什么不使用@State变量showErrorMessage:Bool呢在您的密码和电子邮件有效的功能切换showErrorMessage。因此,如果密码是错误的切换到true,如果密码不是错误的切换到false。
On button click call this showErrorMessage,如果为true则显示文本。