How To Validate TextField Using Swift 2.0 In iOS

Inwizards-blog-img

So you want to know How To Validate TextField Using Swift 2.0 In iOS? Don’t worry Inwizards, a leading Software Development Company has expert developers that has solution to your query.

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.y – MoveKeyboard.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 here.

How To Validate TextField Using Swift 2.0 In iOS

Post navigation


0 0 vote
Article Rating
Subscribe
Notify of
guest
75 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ashd
ashd
7 years ago

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.

Penis verläNgern
Penis verläNgern
7 years ago

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

Get More Information
Get More Information
7 years ago

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

navigate to this site
navigate to this site
7 years ago

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!

This Resource Site
This Resource Site
7 years ago

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!

ow
ow
7 years ago

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.

dypeserm
dypeserm
7 years ago

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.

Bud Pulkrabek
Bud Pulkrabek
7 years ago

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.

24-7cardaccess.com
24-7cardaccess.com
7 years ago

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

a7gg.
a7gg.
7 years ago

A different world is right, but not a bad and very interesting too.

akak
akak
7 years ago

i love this look! Haven’t tried the ball cap yet but I will now!

4ddm
4ddm
7 years ago

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?

7gbf
7gbf
7 years ago

the remote server link doesnt work, i downloaded it.

ThomasAbile
ThomasAbile
6 years ago

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

Carltonliply
Carltonliply
6 years ago

Many thanks for the site, it is loaded with a lot of handy information. This .

ThomasAbile
ThomasAbile
6 years ago

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

HectorNut
HectorNut
6 years ago

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

Carltonliply
Carltonliply
6 years ago

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

ThomasAbile
ThomasAbile
6 years ago

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

HectorNut
HectorNut
6 years ago

Many thanks for sharing, I always learn something new from your posts.

ThomasAbile
ThomasAbile
6 years ago

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

Carltonliply
Carltonliply
6 years ago

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

HectorNut
HectorNut
6 years ago

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

ThomasAbile
ThomasAbile
6 years ago

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

Carltonliply
Carltonliply
6 years ago

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

ThomasAbile
ThomasAbile
6 years ago

I enjoy all your posts. You have done great job

Carltonliply
Carltonliply
6 years ago

Thank you for sharing, I always find out interesting things from your posts.

ThomasAbile
ThomasAbile
6 years ago

Thank you for the site, it is filled with a lot of handy info. This helped me a lot.

ThomasAbile
ThomasAbile
6 years ago

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

Carltonliply
Carltonliply
6 years ago

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.

ThomasAbile
ThomasAbile
6 years ago

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.

Carltonliply
Carltonliply
6 years ago

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

ThomasAbile
ThomasAbile
6 years ago

Many thanks for your great blog. It was very useful. I am so happy I found this.

ThomasAbile
ThomasAbile
6 years ago

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.

MikeMt
MikeMt
6 years ago

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

Carltonliply
Carltonliply
6 years ago

Thanks for sharing, I always learn something new from your posts.

ThomasAbile
ThomasAbile
6 years ago

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

MikeMt
MikeMt
6 years ago

I love all your posts. You’ve done great job

RomeoFueme
RomeoFueme
6 years ago

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.

MikeMt
MikeMt
6 years ago

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

ThomasAbile
ThomasAbile
6 years ago

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.

MikeMt
MikeMt
6 years ago

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

Carltonliply
Carltonliply
6 years ago

I enjoy everything you post. You’ve done fantastic job

MikeMt
MikeMt
6 years ago

I love everything you post. You’ve done really good job

ThomasAbile
ThomasAbile
6 years ago

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

Carltonliply
Carltonliply
6 years ago

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

MikeMt
MikeMt
6 years ago

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

Carltonliply
Carltonliply
6 years ago

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

JeffreyHek
JeffreyHek
6 years ago

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

JeffreyHek
JeffreyHek
6 years ago

Many thanks for helping people get the information they need. Good stuff as always. Keep up the great work!!!

75
0
Would love your thoughts, please comment.x
()
x