Swiftui Email Validation

email validation / SwiftUi

Here is demo for how to add validation.

import Combine
import SwiftUI

struct LoginViewV: View {

@State private var email = ""
@State private var password = ""

var body: some View {
VStack {

TextField("Email", text: $email)
TextField("Password", text: $password)
.onReceive(Just(password), perform: { _ in
// This is for max char. If you want to set limit for character, set here
if password.count >= 12 {
password = String(password.prefix(12))
}
})

Button(action: {

// Show error message here
if let errorMessage = self.validView() {
print(errorMessage)
return
}

// Call login API here
/**
login API
*/

}, label: {
Text("Login")
})
Spacer()
}
}

private func validView() -> String? {
if email.isEmpty {
return "Email is empty"
}

if !self.isValidEmail(email) {
return "Email is invalid"
}

if password.isEmpty {
return "Password is empty"
}

if self.password.count < 8 {
return "Password should be 8 character long"
}

// Do same like other validation as per needed

return nil
}

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)
}
}

SwiftUI Combine ViewModel Email Validation

Let's say you have a simple View like this:

struct ContentView: View {

@StateObject var controller = Controller()

var body: some View {
VStack {
TextField("email", text: $controller.email)
.foregroundColor(controller.inputValid ? .primary : .red)
controller.validationMessage.map { message in
Text(message)
.foregroundColor(.red)
}
}
}
}

and you want to have the logic in your ObservableObject:

class Controller: ObservableObject {

@Published var email = ""
@Published private(set) var validationMessage: String?

var inputValid: Bool {
validationMessage == nil
}


init() {
// you subscribe to any changes to the email field input
$email
// you ignore the first empty value that it gets initialised with
.dropFirst()
// you give the user a bit of time to finish typing
.debounce(for: 0.6, scheduler: RunLoop.main)
// you get rid of duplicated inputs as they do not change anything in terms of validation
.removeDuplicates()
// you validate the input string and in case of problems publish an error message
.map { input in
guard !input.isEmpty else {
return "Email cannot be left empty"
}
guard input.isValidEmail() else {
return "Email is not valid"
}
// in case the input is valid the error message is nil
return nil
}
// you publish the error message for the view to react to
.assign(to: &$validationMessage)
}
}

SwiftUI - Textfield Validation with button and Conditional Statement

Use onChange modifier. Example:


@State var Textfield: String = ""
@State var Answer: String = "Predator"
@State var ShowButton: Bool = false
@State var TextFieldVal: Bool = false


var body: some View {

VStack{
Text(Answer)
.frame(width: 400, height: 40, alignment: .center)
.font(.title)
.foregroundColor(Color.black)


TextField("Type here you answer...", text: $Textfield)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 250, height: 40, alignment: .center)
.background(Color.gray.opacity(0.5).cornerRadius(20))
.foregroundColor(.red)
.font(.headline)


Button {

if TextFieldVal == true {
ShowButton = true
Answer = "That is Correct!"
} else {

Answer = "That is not correct"
}


} label: {
Text("Send")
.frame(width: 250, height: 40)
.background(Color(red: 0.272, green: 0.471, blue: 0.262))
.cornerRadius(20)
.foregroundColor(.white)
.font(.headline)

if ShowButton {
NavigationLink(
destination: Example1(),

label: {
Text("Next")
.frame(width: 120, height: 40)
.background(Color.red)
.cornerRadius(20)
.shadow(radius: 10)
.overlay(
Text("Verder")
.foregroundColor(.white)


)}
)}
}

}
.onChange(of: Textfield) { _ in
if Textfield == "Predator" {
TextFieldVal = true
} else {
TextFieldVal = false
}
}


}


How can i make a TextField validation work in SwiftUI?

Well since you need to frequently update the error message then your prompt property in EmptyField should be Binding, otherwise you'll need to refresh the view.

@Binding var prompt: String

and isFirstNameValid becomes:

var isFirstNameValid: String {
get {
if isValid() {
return ""
}else {
return "Complete first name"
}
}
set {
}
}

Or you can directly use the model in EmptyField, full code:

struct EntryField: View {
var placeHolder: String
@ObservedObject var verifyFieldsViewModel: VerifyFieldsViewModel //edited here
@Binding var field: String
var body: some View {
VStack(alignment: .leading) {
TextField(placeHolder, text: $field).autocapitalization(.none)
Text(verifyFieldsViewModel.isFirstNameValid) //edited here
}
}
}

class VerifyFieldsViewModel : ObservableObject {
@ObservedObject var coreDataViewModel = CoreDataViewModel()
func isValid() -> Bool {
guard coreDataViewModel.savedDetails.first?.firstName?.count ?? 0 > 0 else {
return false
}
return true
}
var isFirstNameValid : String {
if isValid() {
return ""
}else {
return "Complete first name"
}
}
}

@available(iOS 15.0, *)
struct DeliveryView: View {
@ObservedObject var verifyFieldsViewModel = VerifyFieldsViewModel()
@StateObject var coreDataViewModel = CoreDataViewModel()
var body: some View {
let firstName = Binding(
get: {coreDataViewModel.savedDetails.first?.firstName ?? ""},
set: {coreDataViewModel.savedDetails.first?.firstName = $0})
ScrollView {
VStack(alignment: .leading) {
Text("Nume")
.foregroundColor(.orange)
EntryField(placeHolder: "Popescu", verifyFieldsViewModel: verifyFieldsViewModel, field: firstName) //edited here
.onSubmit {
coreDataViewModel.saveContext()
}
}
}
}
}

How to validate an e-mail address in swift?

I would use NSPredicate:

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)
}

for versions of Swift earlier than 3.0:

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)
}

for versions of Swift earlier than 1.2:

func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}

SwiftUI: TextField conditional validation

the problem as I see it, is that you do not recalculate the "minimumXIsGood" value when you change the picker from plot to map and vice versa. Try this:

    Picker(selection: $addPatternVM.type, label: Text("")) {
Text("Plot").tag("plot")
Text("Map").tag("map")
}.pickerStyle(SegmentedPickerStyle())
.onChange(of: addPatternVM.type) { _ in
addPatternVM.isMinimumXGood(newValue: addPatternVM.minimumXString)
}

Email & Phone Validation in Swift

Yes your Error is below in XCode 6.1

Xcode error screenshot

This error is occurs because of if conditional have to Bool return type, but in Your if condition Return type is NSPredicate so that you got error swift: Bound value in a conditional binding must be of Optional type you can solve as below.

    var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}

Email-Validations in Swift.

    func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}

Use of Email-validation:

    if isValidEmail("kirit@gmail.com"){
print("Validate EmailID")
}
else{
print("invalide EmailID")
}

Phone-Number Validation in Swift

    func validate(value: String) -> Bool {
let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}


Related Topics



Leave a reply



Submit