gpt4 book ai didi

ios - SwiftUI 电子邮件验证

转载 作者:行者123 更新时间:2023-12-03 20:08:02 24 4
gpt4 key购买 nike

如何使用 swiftUI 完成电子邮件验证?

TextField("Please enter your e-mail", text: self.$email)
.modifier(ClearButton(text: $email))
.font(.headline)
.padding(10)
.foregroundColor(.black)
.background(Color.white)
.frame(width: 300, height: 40, alignment: .center)
.cornerRadius(20)

最佳答案

只需使用 onEditingChanged 即可完成验证任何 TextField .

下面的代码用于电子邮件验证,但它可以用于任何其他验证。

当用户完成并存在文本字段时,我验证文本,如果未验证,则删除文本下方有错误的文本。

import SwiftUI
struct ContentView: View {

@State private var emailString : String = ""
@State private var textEmail : String = ""
@State private var isEmailValid : Bool = true

var body: some View {
VStack {
TextField("email...", text: $textEmail, onEditingChanged: { (isChanged) in
if !isChanged {
if self.textFieldValidatorEmail(self.textEmail) {
self.isEmailValid = true
} else {
self.isEmailValid = false
self.textEmail = ""
}
}
})
//.modifier(ClearButton(text: $email))
.font(.headline)
.padding(10)
.foregroundColor(.black)
.background(Color.white)
.frame(width: 300, height: 40, alignment: .center)
.cornerRadius(20)
.autocapitalization(.none)

if !self.isEmailValid {
Text("Email is Not Valid")
.font(.callout)
.foregroundColor(Color.red)
}
}
}

func textFieldValidatorEmail(_ string: String) -> Bool {
if string.count > 100 {
return false
}
let emailFormat = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" + "z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
//let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: string)
}}
onEditingChanged :当用户点击这个时, isChanged = true , 当用户退出并转到其他地方时, isChange = false .

关于ios - SwiftUI 电子邮件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59988892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com