Email Validation,Password Validation,URL Validation using Regex - Swift 4, iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

9 Sep 2017

Email Validation,Password Validation,URL Validation using Regex - Swift 4, iOS

Now a days, every app is using signup and login method. For that we need to do Field Validation, so that we can avoid fake signups and logins.

In this article we are going to cover following validation :

1. Email Validation. (iosrevisited@gmail.com)
2. Password Validation. (Password@22)
3. URL Validation. (http://iosrevisited.blogspot.com)

This Article Covers Following Related questions  :

How to validate an e-mail address in swift?
Email & Phone Number Validation in Swift 3.?
swift email address validation -ios
url validation in swift3
swift 3 validate email address
password validation in swift
text field validation in swift
password validation in swift 3
email validation in swift3
password length validation in swift


 Email Validation,Password Validation,URL Validation using Regex - Swift 4, iOS


1. Email Validation :

We are using regex for validating email.

Some valid emails :

abc@gmail.com, hello@yahoo.com

Add the following method for email validation :

func isValidEmail(email: String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: email)
    return result
}

Then call the above method as following :
var isValid = isValidEmail(email: textField.text!)

If valid it will give true otherwise false.

2. Password Validation :

There are different formats for password. Here we will do most commonly used format.

- Password length 6 to 16.
- One Alphabet in Password.
- One Special Character in Password.

Some valid Password :

letmein@11, swift&ios

Add the following method for Password validation :
func isValidPassword(password: String) -> Bool {
    let passwordRegEx = "^(?=.*[a-z])(?=.*[$@$#!%*?&])[A-Za-z\\d$@$#!%*?&]{6,16}"
    let passwordTest = NSPredicate(format:"SELF MATCHES %@", passwordRegEx)
    let result = passwordTest.evaluate(with: password)
    return result
}

Then call the above method as following :
var isValid = isValidPassword(email: textField.text!)

If valid it will give true otherwise false.

3. URL Validation :

We are validating url using regex.

Some valid Url's :

http://iosrevisited.blogspot.com, http://adeepdrive.com.

Add the following method for URL validation :
func isValidUrl(url: String) -> Bool {
    let urlRegEx = "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
    let urlTest = NSPredicate(format:"SELF MATCHES %@", urlRegEx)
    let result = urlTest.evaluate(with: url)
    return result
}

Then call the above method as following :
var isValid = isValidUrl(email: textField.text!)

If valid it will give true otherwise false.

Download sample project with examples :

1 comment:

Post Top Ad