Sam
Sam

Reputation: 479

Check emali validation as soon as I move to the next text field

I have a text field for UserEmailId. Below this UserEmailId I have other text fields. I don't want to validate the Email ID after clicking on signup button, I want to check validation as soon as I click on enter and move to next text field.

I only know how to do the validation after all the fields are filled up. Please suggest how to validate as soon as I move to next text field after entering the email address.

@IBOutlet weak var emailText: UITextField!

@IBAction func logIn(sender: AnyObject)
{    
    let validLogin = isValidEmail(emailText.text)    
    if validLogin
        println("User entered valid input")    
    else     
        println("Invalid email address")    
}

func isValidEmail(testStr:String) -> Bool 
{    
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"    
    let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)    
    let result = range != nil ? true : false    
    return result
}

Upvotes: 0

Views: 136

Answers (3)

Kuldeep Singh
Kuldeep Singh

Reputation: 37

Email check function return true or false

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

        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: text)
    }

TextFields Delegate

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == txtEmail{
        if self.isValidEmail(text:textField.text ?? ""){
            //Valid Email
        }
        else{
            //Invalid Email
        }
    }

}

Upvotes: -1

ebby94
ebby94

Reputation: 3152

Let's assume you have two text fields. One for Email address and another for password. Set the tag of emailTextField to 0 and the tag of passwordTextField to 1. Now what you want to do is validate right after the textfield ends editing. The below code should point you in the right direction. Add UITextFieldDelegate to your class and don't forget to set the delegates of your textfield to self.

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.tag == 0{
        if isValidEmail(testStr:textField.text!){
            //Do your stuff
        }
        else{
            //Do something else
        }
    }
    else if textField.tag == 1{
        // Do your other validation
    }
}

Upvotes: 2

Gurinder Batth
Gurinder Batth

Reputation: 663

The best way is add the Validation Methods in the following Delegate methods func textFieldShouldEndEditing(UITextField) & func textFieldDidEndEditing(UITextField) add the if conditions in the delegate method to check which text field is editing and then add the validation

are you got the point or i will add coding samples here

Upvotes: 2

Related Questions