How To Validate TextField Using Swift 2.0 In iOS

Inwizards-blog-img

Objective:- Make a registration form with apply all required validation.

Create a new project

Open Xcode , create a new “Single Page Application” and select Swift as the programming language.

Add a TextField property

Open the ViewController.swift class and add a new tableview instance variable below the class declaration.

@IBOutlet weak var firstName: UITextField!

@IBOutlet weak var LastName: UITextField!

@IBOutlet weak var UserName: UITextField!

@IBOutlet weak var DateofBirth: UITextField!

@IBOutlet weak var MobileNo: UITextField!

@IBOutlet weak var password: UITextField!

@IBOutlet weak var Cpassword: UITextField!

@IBOutlet weak var DOB: UIDatePicker!

@IBOutlet weak var emailID: UITextField!

Add Source File from project directory.


TextFieldValidation.swift

ValidationError.swift

ValidationErrorType.swift

ValidationFactory.swift

ValidationRule.swift

ValidationRuleType.swift

Validator.swift

Validation.swift

Confirm to the TextField Delegate.

To conform to the UITextFieldDelegate,ValidationFieldDelegate just add them separated by colons after UIViewController in the class declaration. This was a bit confusing at first but the new protocol syntax is cleaner.

class ViewController: UIViewController,UITextFieldDelegate,ValidationFieldDelegate

{

…….

}


Add a TextField in your view controller

Search in the component library(It should be in the lower right corner) for TextField and then drag and drop it on the view.

Connect the Interface Builder Outlets

Connect the referencing delegate outlets.
We can connect the respective outlets using interface builder by right clicking on the textfield view and dragging each outlet on the view controller.

Now Goto ViewController.swift file

import UIKit

struct MoveKeyboard {

static let KEYBOARD_ANIMATION_DURATION : CGFloat = 0.3

static let MINIMUM_SCROLL_FRACTION : CGFloat = 0.2;

static let MAXIMUM_SCROLL_FRACTION : CGFloat = 0.8;

static let PORTRAIT_KEYBOARD_HEIGHT : CGFloat = 216;

static let LANDSCAPE_KEYBOARD_HEIGHT : CGFloat = 162;

}

class ViewController:UIViewController,UITextFieldDelegate,ValidationFieldDelegate,UIAlertViewDelegate

{

//************************************************************************************************

// MARK: Create Outlets and Proprty.

//************************************************************************************************

@IBOutlet weak var firstName: UITextField!

@IBOutlet weak var LastName: UITextField!

@IBOutlet weak var UserName: UITextField!

@IBOutlet weak var DateofBirth: UITextField!

@IBOutlet weak var MobileNo: UITextField!

@IBOutlet weak var password: UITextField!

@IBOutlet weak var Cpassword: UITextField!

@IBOutlet weak var DOB: UIDatePicker!

@IBOutlet weak var emailID: UITextField!

var animateDistance:CGFloat!

var validator = Validator()

var databasePath = NSString()

var Fields = [“Email”,“Phone”,“Password”,“Cpassword”,“UserID”,“fname”,“Lname”,“dob”]

//*************************************************************************************************



// MARK: viewDidLoad

//*************************************************************************************************

override func viewDidLoad() {

super.viewDidLoad()

self.setUpUI()

}

func setUpUI(){

emailID.delegate = self

MobileNo.delegate = self

password.delegate = self

Cpassword.delegate = self

UserName.delegate = self

firstName.delegate = self

LastName.delegate = self

DateofBirth.delegate = self

// MARK: Apply Validation on textfield.

validator.registerFieldByKey(Fields[0],textField: emailID,rules: [.Required, .Email])

validator.registerFieldByKey(Fields[1],textField: MobileNo,rules: [.Required, .PhoneNumber])

validator.registerFieldByKey(Fields[2],textField: password,rules: [.Required, .Password])

validator.registerFieldByKey(Fields[3],textField: Cpassword,rules: [.Required, .Password])

validator.registerFieldByKey(Fields[4],textField: UserName,rules: [.Required, .MinLength])

validator.registerFieldByKey(Fields[5],textField: firstName,rules: [.Required, .MaxLength])

validator.registerFieldByKey(Fields[6],textField: LastName,rules: [.Required, .MaxLength])

}

//*************************************************************************************************

// MARK: Use datePicker for valueChanged on textField.

//*************************************************************************************************

@IBAction func dobtext(sender: UITextField)

{

let datePickerView : UIDatePicker = UIDatePicker()

datePickerView.datePickerMode = UIDatePickerMode.Date

sender.inputView = datePickerView

datePickerView.addTarget(self, action: Selector(“handleDatePicker:”), forControlEvents:UIControlEvents.ValueChanged)

}

func handleDatePicker(sender: UIDatePicker)

{

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = “dd MMM yyyy”

DateofBirth.text = dateFormatter.stringFromDate(sender.date)

}

//**************************************************************************************************

// MARK: TextField Delegate Method For Moving Keyboard.

//**************************************************************************************************

func textFieldDidBeginEditing(textField: UITextField) {

let textFieldRect : CGRect = self.view.window!.convertRect(textField.bounds, fromView: textField)

let viewRect : CGRect = self.view.window!.convertRect(self.view.bounds, fromView: self.view)

let midline : CGFloat = textFieldRect.origin.y + 0.5 * textFieldRect.size.height

let numerator : CGFloat = midline – viewRect.origin.yMoveKeyboard.MINIMUM_SCROLL_FRACTION * viewRect.size.height

let denominator : CGFloat = (MoveKeyboard.MAXIMUM_SCROLL_FRACTION –MoveKeyboard.MINIMUM_SCROLL_FRACTION) * viewRect.size.height



var heightFraction : CGFloat = numerator / denominator

if heightFraction < 0.0 {

heightFraction = 0.0

} else if heightFraction > 1.0 {

heightFraction = 1.0

}

let orientation : UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation

if (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown) {

animateDistance = floor(MoveKeyboard.PORTRAIT_KEYBOARD_HEIGHT * heightFraction)

} else {

animateDistance = floor(MoveKeyboard.LANDSCAPE_KEYBOARD_HEIGHT * heightFraction)

}

var viewFrame : CGRect = self.view.frame

viewFrame.origin.y -= animateDistance

UIView.beginAnimations(nil, context: nil)

UIView.setAnimationBeginsFromCurrentState(true)

UIView.setAnimationDuration(NSTimeInterval(MoveKeyboard.KEYBOARD_ANIMATION_DURATION))

self.view.frame = viewFrame

UIView.commitAnimations()

}

func textFieldDidEndEditing(textField: UITextField) {

var viewFrame : CGRect = self.view.frame

viewFrame.origin.y += animateDistance

UIView.beginAnimations(nil, context: nil)

UIView.setAnimationBeginsFromCurrentState(true)

UIView.setAnimationDuration(NSTimeInterval(MoveKeyboard.KEYBOARD_ANIMATION_DURATION))

self.view.frame = viewFrame

UIView.commitAnimations()

}

func textFieldShouldReturn(textField: UITextField) -> Bool {

textField.resignFirstResponder()

return true

}

func DismissKeyboard(){

emailID.resignFirstResponder()

MobileNo.resignFirstResponder()

UserName.resignFirstResponder()

UserName.resignFirstResponder()

LastName.resignFirstResponder()

password.resignFirstResponder()

Cpassword.resignFirstResponder()

}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

if(string == “\n”){

emailID.resignFirstResponder()

MobileNo.resignFirstResponder()

UserName.resignFirstResponder()

UserName.resignFirstResponder()

LastName.resignFirstResponder()

password.resignFirstResponder()

Cpassword.resignFirstResponder()

return false

}

return true

}

override func prefersStatusBarHidden() -> Bool {

return true

}

//*******************************************************************************************************************************************//

// MARK: Validation Delegate Function.

//*******************************************************************************************************************************************//

func validationFieldFailed(key:String, error:ValidationError)

{

//set error textfield border to red.

_ = UITextField(frame: CGRectMake(0.0, 0.0, 200.0, 44.0))

error.textField.layer.cornerRadius = 8.0



error.textField.layer.masksToBounds = true

error.textField.layer.borderColor = UIColor.redColor().CGColor

error.textField.layer.borderWidth = 2.0

error.textField

}

func validationFieldSuccess(key:String, validField:UITextField)

{

//set valid textfield border to green

_ = UITextField(frame: CGRectMake(0.0, 0.0, 200.0, 44.0))

validField.layer.cornerRadius = 8.0

validField.layer.masksToBounds = true

validField.layer.borderColor = UIColor.greenColor().CGColor

validField.layer.borderWidth = 2.0

validField

}

@IBAction func validateField(sender: AnyObject)

{

switch (sender as! UITextField)

{

case emailID :

validator.validateFieldByKey((Fields[0]), delegate: self)

break

case MobileNo :

validator.validateFieldByKey((Fields[1]), delegate: self)

break

case password :

validator.validateFieldByKey((Fields[2]), delegate: self)

break

case Cpassword :

validator.validateFieldByKey((Fields[3]), delegate: self)

break

case UserName :

validator.validateFieldByKey((Fields[4]), delegate: self)

break

case firstName :

validator.validateFieldByKey((Fields[5]), delegate: self)

break

case LastName :

validator.validateFieldByKey((Fields[6]), delegate: self)

break

default :

print(“no fields to validate”)

}

}

@IBAction func SubmitAction(sender: AnyObject)

{

if (firstName == nil || firstName.text == “”)

{



validator.validateFieldByKey(Fields[5], delegate: self)

let alert = UIAlertView(title: “Error”, message: “Please Enter Your First Name”, delegate: self, cancelButtonTitle: “OK”)

alert.show()

}

else if (LastName == nil || LastName.text == “”)

{ validator.validateFieldByKey(Fields[6], delegate: self)

let alertview = UIAlertView(title: “Error”, message: “Please Enter Your Last Name”, delegate: self, cancelButtonTitle: “ok”)

alertview.show()

}

else if (UserName == nil || UserName.text == “”)

{

validator.validateFieldByKey(Fields[4], delegate: self)

let alertview = UIAlertView(title: “Error”, message: “UserID Short Should be 5 Char. “, delegate: self, cancelButtonTitle: “ok”)

alertview.show()

}

else if (MobileNo == nil || MobileNo.text == “”)

{

validator.validateFieldByKey(Fields[1], delegate:self)

let alertview = UIAlertView(title: “Error”, message: “Please Enter Mobile No. and must be 10 digit “, delegate:self, cancelButtonTitle: “ok”)

alertview.show()

}

else if (emailID == nil || emailID.text == “”)

{

validator.validateFieldByKey(Fields[0], delegate:self)

let alertview = UIAlertView(title: “Error”, message: “Please Enter Your Email Address”, delegate: self, cancelButtonTitle: “ok”)

alertview.show()

}

else if (password == nil || password.text == “”)

{ validator.validateFieldByKey(Fields[2], delegate: self)

let alertview = UIAlertView(title: “Error”, message: “Please Enter Your Password “, delegate: self, cancelButtonTitle: “ok”)

alertview.show()

}

else if (Cpassword == nil || Cpassword.text == “”)

{ validator.validateFieldByKey(Fields[3], delegate: self)

let alertview = UIAlertView(title: “Error”, message: “Please Enter Confirm Password “, delegate: self, cancelButtonTitle: “ok”)

alertview.show()

}

else if(password.text != Cpassword.text)

{

let alert = UIAlertView(title: “Alert”, message: “Password And Confirm Password Should Be Same”, delegate:self, cancelButtonTitle: “Cancel”,otherButtonTitles: “Ok”)

alert.show()

password.text = “”

Cpassword.text = “”

}



else{

let alert = UIAlertView(title: “Success”, message: “All Validation is correct”, delegate: self, cancelButtonTitle:nil,otherButtonTitles: “Ok”)

alert.show()

}

}

}

You can download Demo project from below given Url.

https://goo.gl/D0E6Q2

How To Validate TextField Using Swift 2.0 In iOS

Post navigation


75 thoughts on “How To Validate TextField Using Swift 2.0 In iOS

  1. You can use the delegate methods to prevent the user from starting or stopping the editing process or to validate text as it is typed.

  2. What a material of un-ambiguity and preserveness of valuable know-how regarding
    unpredicted feelings.

  3. Amazing! Its really awesome piece of writing, I have got
    much clear idea regarding from this paragraph.

  4. First of all I would like to say great blog! I had a quick question which I’d like to ask if you do not mind.

    I was interested to know how you center yourself
    and clear your mind prior to writing. I have had a difficult time clearing my thoughts in getting my ideas
    out there. I truly do enjoy writing however it just seems like the first 10 to 15 minutes are wasted simply just trying to figure out
    how to begin. Any ideas or hints? Many thanks!

  5. Whoa! This blog looks just like my old one! It’s on a completely different subject but it
    has pretty much the same page layout and design. Great choice of colors!

  6. Its not my first time to pay a visit this website, i am
    browsing this site dailly and obtain pleasant facts from here all the
    time.

  7. What’s Going down i am new to this, I stumbled upon this I have found It absolutely useful and it has helped me out loads. I hope to give a contribution & help different users like its helped me. Great job.

  8. I will right away grab your rss feed as I can’t find your e-mail subscription link or newsletter service. Do you’ve any? Please let me know in order that I could subscribe. Thanks.

  9. How to get textField id in doneButtonAction method while using multiple numPad keyboard textFields in swift?

  10. My first day on Odimune and I am geting an allergic reaction. It is similar to that of a sulphur reaction, which I am allergic to. What should I do with the Odimune?

  11. It is an excellent resource!A lot of useful information and handy ideas, thanks =)

  12. Great post\Nice post, I love it very much.I was very lucky to discover your site. It has a lot of useful info!

  13. I am impressed. I don’t think I’ve met anyone who understands as much about this as you do. You should make a career of it, really, great site

  14. Many thanks for sharing with us, I always learn interesting things from your posts.

  15. Many thanks for helping people get the information they need. Great stuff as usual. Keep up the great work!!!

  16. Thank you for helping people get the information they need. Good stuff as always. Keep up the great work!!!

  17. This is a really great site!A lot of useful information and handy tips, thanks a lot =)

  18. It’s an amazing article. This site is loaded with lots of interesting things, it helped me in many ways.

  19. it’s my first time visiting your website and I am very interested. Thanks for sharing and keep up 😉

  20. it’s my first time visiting your blog and I am very fascinated. Thank you for sharing and keep up 😉

  21. Many thanks for sharing with us, I always discover interesting things from your posts.

  22. Great website, how do you find all this info?I’ve read through a couple of posts on your website and I really like your writing style. Thanks a million, keep up the good work.

  23. Not too long ago I have come across one article which I think you might find interesting. Someone will take a steaming dump all over it, but it clarified some of my questions.

  24. Thanks for a really impressive blog. It was very useful. I am so happy I came across this.

  25. Recently I have come across one article which I think you might find helpful. Somebody may take a steaming dump all over it, however it answered some of my questions.

  26. This is a very good article. This site is loaded with lots of useful things, it helped me in many ways.

  27. Many thanks for the site, it truly is loaded with so much useful info. This helped me a lot.

  28. Custom made paper composing program – a requirement of in the present day | Once you think that like property job as crafting essay occupies your time and efforts – be courageous to prevent it with.

  29. Wow! This might be one of the most useful things on the topic I’ve ever come across. Thanks for your hard work.

  30. Amazing website, how do you find all this info?I’ve read through a couple of articles on your website and I like your writing style. Thanks a million, keep up the great work.

  31. Good post, I love it a lot.I was really lucky to find your website. It has a lot of helpful information!

  32. Thanks for your fantastic blog. It was very helpful. I am so glad I came across this.

  33. It’s an amazing post. This website has lots of useful things, it made it easier for me in many ways.

  34. Whoa! This may be by far the most helpful thing on the topic I have ever read. Many thanks for your effort.

  35. It is a good article. This website has lots of interesting things, it really helped me in many ways.

  36. It is a good post. This site is loaded with lots of useful things, it helped me in many ways.

  37. Thanks for helping people get the information they need. Great stuff as usual. Keep up the great work!!!

  38. I am impressed. I do not think I know anybody who knows so much about the topic. You need to make a career of it, honestly, great blog

  39. This is an amazing post. This site is loaded with lots of interesting things, it helped me in many ways.

  40. Good post, I love it very much.I was really lucky to discover your site. It’s got so much useful information!

  41. it’s my first time visiting your site and I’m very fascinated. Thank you for sharing and keep up 😉

  42. Great website, how do u find all this info?I’ve read through a few articles on your website and I love your writing style. Thanks a million, keep up the good work.

  43. Amazing site, how do you get all this information?I have read a couple of articles on your site and I really like your style. Thanks a million, keep up the good work.

  44. Great post\Nice post, i like it very much.I was pretty lucky to discover your website. There’s a lot of useful info!

  45. I glanced through this website and there’s so much handy information, bookmarked 🙂

  46. I’ve discovered a lot of useful info on your site this page in particular. Thanks for posting.

  47. Thanks for a really great blog. It was actually very helpful. I am just so glad I came across this.

Leave a Reply

Your email address will not be published. Required fields are marked *