Email & Phone Validation in Swift
Yes your Error is below in XCode 6.1
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
}
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
}
How to validate American Phone Format in Swift 4?
Use this regular expression:
(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}
Code:
let phoneNumber = "+1 (123) 456-7890" //Replace it with the Phone number you want to validate
let range = NSRange(location: 0, length: phoneNumber.count)
let regex = try! NSRegularExpression(pattern: "(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}")
if regex.firstMatch(in: phoneNumber, options: [], range: range) != nil{
print("Phone number is valid")
}else{
print("Phone number is not valid")
}
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
}
Validation of email in swift iOS application
You can validate email using a simple regex function which returns true
if it's valid otherwise false
You can validate it when user hits Done/Enter on keyboard event, such as editingDidEnd
. You can bind it from storyboard to class file like,
@IBAction func onPressDone(sender: UITextField){
if txtEmaildAddress.text.isEmpty {
println("enter email address") //prompt ALert or toast
}
else if self.validate(txtEmaildAddress.text) {
println("Invalid email address") // prompt alert for invalid email
}
}
func validate(YourEMailAddress: String) -> Bool {
let REGEX: String
REGEX = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", REGEX).evaluateWithObject(YourEMailAddress)
}
May help this method to validate easily.
HTH, Enjoy Coding !!
how to check the entered email is in email format
Hope it helps:
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
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.evaluateWithObject(testStr)
return result
}
In your code:
import UIKit
extension String {
func matchPattern(patStr:String)->Bool {
var isMatch:Bool = false
do {
let regex = try NSRegularExpression(pattern: patStr, options: [.CaseInsensitive])
let result = regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, characters.count))
if (result != nil)
{
isMatch = true
}
}
catch {
isMatch = false
}
return isMatch
}
}
class RegisterVC: UIViewController {
@IBOutlet weak var EmailField: UITextField!
@IBOutlet weak var LocationField: UITextField!
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passWordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
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.evaluateWithObject(testStr)
return result
}
@IBAction func SignUpBtnPress(sender: AnyObject) {
let Email:NSString = EmailField.text!
let Location:NSString = LocationField.text!
let username:NSString = userNameField.text!
let password:NSString = passWordField.text!
let confirm_password:NSString = confirmPasswordField.text!
if isValidEmail(Email) == true{
{
print("this is e-mail!")
}
else if ( Email.isEqualToString("") || Location.isEqualToString("") || username.isEqualToString("") || password.isEqualToString("") || confirm_password.isEqualToString("") ) {
let alertController = UIAlertController(title: "Alert", message: "All Field Are Mnditory.", preferredStyle: UIAlertControllerStyle.Alert)
let DestructiveAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Settings")
}
alertController.addAction(DestructiveAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else if ( !password.isEqual(confirm_password) ) {
let alertController = UIAlertController(title: "Alert", message: "Password Din't Match.", preferredStyle: UIAlertControllerStyle.Alert)
let DestructiveAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Password Din't Match")
}
alertController.addAction(DestructiveAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
print("login sucess")
}
Related Topics
Set Custom Images to the Uibarbuttonitem But It Doesn't Show Any Image
How to Do a Native "Pulse Effect" Animation on a Uibutton - iOS
Contentview Not Indenting in iOS 6 Uitableviewcell Prototype Cell
iOS Horizontal Slideview with Vertical Menu
Grouped Uitableview Remove Outer Separator Line
Warning: Output of Vertex Shader 'V_Gradient' Not Read by Fragment Shader
How to Download Files from Uiwebview and Open Again
Pushing a Navigation Controller Is Not Supported
iOS Push Notification Banner Shown Twice for a Single Push
Capture Uiview and Save as Image
Running Xcodebuild from a Forked Terminal
Hide Keyboard When Scroll Uitableview
Front Facing Camera in Uiimagepickercontroller
How to Dismiss the iOS Keyboard
Custom Uifont Baseline Shifted
App Store Connect Message: Your Account Will Soon Need to Be Migrated to Federated Auth