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.
Also Check out How to Search Photos Using Flickr API In Swift 2.0?
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.
What a material of un-ambiguity and preserveness of valuable know-how regarding
unpredicted feelings.
Amazing! Its really awesome piece of writing, I have got
much clear idea regarding from this paragraph.
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!
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!
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.
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.
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.
How to get textField id in doneButtonAction method while using multiple numPad keyboard textFields in swift?
A different world is right, but not a bad and very interesting too.
i love this look! Haven’t tried the ball cap yet but I will now!
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?
the remote server link doesnt work, i downloaded it.
It is an excellent resource!A lot of useful information and handy ideas, thanks =)
Many thanks for the site, it is loaded with a lot of handy information. This .
Great post\Nice post, I love it very much.I was very lucky to discover your site. It has a lot of useful info!
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
Many thanks for sharing with us, I always learn interesting things from your posts.
Many thanks for helping people get the information they need. Great stuff as usual. Keep up the great work!!!
Many thanks for sharing, I always learn something new from your posts.
Thank you for helping people get the information they need. Good stuff as always. Keep up the great work!!!
This is a really great site!A lot of useful information and handy tips, thanks a lot =)
It’s an amazing article. This site is loaded with lots of interesting things, it helped me in many ways.
it’s my first time visiting your website and I am very interested. Thanks for sharing and keep up 😉
it’s my first time visiting your blog and I am very fascinated. Thank you for sharing and keep up 😉
I enjoy all your posts. You have done great job
Thank you for sharing, I always find out interesting things from your posts.
Thank you for the site, it is filled with a lot of handy info. This helped me a lot.
Many thanks for sharing with us, I always discover interesting things from your posts.
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.
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.
Thanks for a really impressive blog. It was very useful. I am so happy I came across this.
Many thanks for your great blog. It was very useful. I am so happy I found this.
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.
This is a very good article. This site is loaded with lots of useful things, it helped me in many ways.
Thanks for sharing, I always learn something new from your posts.
Many thanks for the site, it truly is loaded with so much useful info. This helped me a lot.
I love all your posts. You’ve done great job
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.
Wow! This might be one of the most useful things on the topic I’ve ever come across. Thanks for your hard work.
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.
Good post, I love it a lot.I was really lucky to find your website. It has a lot of helpful information!
I enjoy everything you post. You’ve done fantastic job
I love everything you post. You’ve done really good job
Thanks for your fantastic blog. It was very helpful. I am so glad I came across this.
It’s an amazing post. This website has lots of useful things, it made it easier for me in many ways.
Whoa! This may be by far the most helpful thing on the topic I have ever read. Many thanks for your effort.
It is a good article. This website has lots of interesting things, it really helped me in many ways.
It is a good post. This site is loaded with lots of useful things, it helped me in many ways.
Many thanks for helping people get the information they need. Good stuff as always. Keep up the great work!!!