我在生成错误文本时遇到了问题。
@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()结果应该是,当我输入不适当的电子邮件/密码并单击登录时会出现错误文本
以上代码是我的尝试。
我可能犯了一些基本的错误,希望你能正确理解。我很感谢你们的关注,谢谢大家
发布于 2022-04-17 08:46:37
为什么不在密码和电子邮件有效函数中使用@State显示错误消息:Bool来切换showErrorMessage。因此,如果密码是错误的,切换到true,如果密码没有错误,切换到false。
在按钮上单击“调用此showErrorMessage”,如果为真,则显示文本。
https://stackoverflow.com/questions/71899557
复制相似问题