what is better approach to UITextField validations on iOS?How can I make a UITextField move up when the keyboard is present - on starting to edit?UITextField text change eventHow to override UIView initializer in Swift 1.0Swift 2 iOS 9 animation disappears after button text changedIssues with casting celltypes to dequeueAdding a custom UIViewcontroller to subview programmatically but getting an error message “Cannot convert value of type…”How to save the properties of UILable in UIView in swift?How to optimize UITableViewCell, because my UITableView lagsMapBox - detect zoomLevel changesWhy there is an extra UIView when adding an XIB view from the Interface Builder

Should I ask for permission to write an expository post about someone's else research?

The equation of motion for a scalar field in curved spacetime in terms of the covariant derivative

AsyncDictionary - Can you break thread safety?

Can a fight scene, component-wise, be too complex and complicated?

Double redundancy for the Saturn V LVDC computer memory, how were disagreements resolved?

How are you supposed to know the strumming pattern for a song from the "chord sheet music"?

How is this kind of structure made?

Is there a way to unplug the Raspberry pi safely without shutting down

Generate Brainfuck for the numbers 1–255

function evaluation - I don't get it

Bitcoin successfully deducted on sender wallet but did not reach receiver wallet

changing number of arguments to a function in secondary evaluation

English - Acceptable use of parentheses in an author's name

What is the maximum number of PC-controlled undead?

Who are these characters/superheroes in the posters from Chris's room in Family Guy?

What does Apple mean by "This may decrease battery life"?

Visa National - No Exit Stamp From France on Return to the UK

How can I solve for the intersection points of two ellipses?

How can you evade tax by getting employment income just in equity, then using this equity as collateral to take out loan?

Y2K... in 2019?

Does a code snippet compile? Or does it get compiled?

Withdrew when Jimmy met up with Heath

Acceptable to cut steak before searing?

Tikzpicture - finish drawing a curved line for a cake slice



what is better approach to UITextField validations on iOS?


How can I make a UITextField move up when the keyboard is present - on starting to edit?UITextField text change eventHow to override UIView initializer in Swift 1.0Swift 2 iOS 9 animation disappears after button text changedIssues with casting celltypes to dequeueAdding a custom UIViewcontroller to subview programmatically but getting an error message “Cannot convert value of type…”How to save the properties of UILable in UIView in swift?How to optimize UITableViewCell, because my UITableView lagsMapBox - detect zoomLevel changesWhy there is an extra UIView when adding an XIB view from the Interface Builder






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have to make validation on ui text field which used in library called RSFloatInputView.



Here is my xib



import UIKit
import RSFloatInputView

class TextInputLayout: UIView

@IBOutlet weak var revealButton: UIButton!
@IBOutlet weak var warningLabel: UILabel!
@IBOutlet weak var rsFloatingView: RSFloatInputView!
var contentView: UIView?

override init(frame: CGRect)
super.init(frame: frame)
xibSetup()


required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
xibSetup()


func xibSetup()
contentView = loadViewFromNib()
contentView!.frame = bounds
contentView!.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
addSubview(contentView!)


func loadViewFromNib() -> UIView!
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TextInputLayout", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
revealButton.tintColor = Color.grayColor()
warningLabel.textColor = UIColor.red

return view




I want to implement this in this view controller, when i click on next button



import UIKit
import DLRadioButton

class SecureWalletViewController: UIViewController,UITextFieldDelegate

@IBOutlet weak var securityPinStackView: UIStackView!
@IBOutlet weak var securityPin: TextInputLayout!
@IBOutlet weak var confirmSecurityPin: TextInputLayout!

@IBAction func onNextButtonTap(_ sender: Any)



func textInputLayout(at index:Int) -> TextInputLayout
return securityPinStackView.arrangedSubviews[index] as! TextInputLayout











share|improve this question


























  • its for empty validation or else

    – Anbu.Karthik
    Mar 27 at 7:12











  • empty and confirm password

    – vikas patidar
    Mar 27 at 7:21

















1















I have to make validation on ui text field which used in library called RSFloatInputView.



Here is my xib



import UIKit
import RSFloatInputView

class TextInputLayout: UIView

@IBOutlet weak var revealButton: UIButton!
@IBOutlet weak var warningLabel: UILabel!
@IBOutlet weak var rsFloatingView: RSFloatInputView!
var contentView: UIView?

override init(frame: CGRect)
super.init(frame: frame)
xibSetup()


required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
xibSetup()


func xibSetup()
contentView = loadViewFromNib()
contentView!.frame = bounds
contentView!.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
addSubview(contentView!)


func loadViewFromNib() -> UIView!
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TextInputLayout", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
revealButton.tintColor = Color.grayColor()
warningLabel.textColor = UIColor.red

return view




I want to implement this in this view controller, when i click on next button



import UIKit
import DLRadioButton

class SecureWalletViewController: UIViewController,UITextFieldDelegate

@IBOutlet weak var securityPinStackView: UIStackView!
@IBOutlet weak var securityPin: TextInputLayout!
@IBOutlet weak var confirmSecurityPin: TextInputLayout!

@IBAction func onNextButtonTap(_ sender: Any)



func textInputLayout(at index:Int) -> TextInputLayout
return securityPinStackView.arrangedSubviews[index] as! TextInputLayout











share|improve this question


























  • its for empty validation or else

    – Anbu.Karthik
    Mar 27 at 7:12











  • empty and confirm password

    – vikas patidar
    Mar 27 at 7:21













1












1








1


1






I have to make validation on ui text field which used in library called RSFloatInputView.



Here is my xib



import UIKit
import RSFloatInputView

class TextInputLayout: UIView

@IBOutlet weak var revealButton: UIButton!
@IBOutlet weak var warningLabel: UILabel!
@IBOutlet weak var rsFloatingView: RSFloatInputView!
var contentView: UIView?

override init(frame: CGRect)
super.init(frame: frame)
xibSetup()


required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
xibSetup()


func xibSetup()
contentView = loadViewFromNib()
contentView!.frame = bounds
contentView!.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
addSubview(contentView!)


func loadViewFromNib() -> UIView!
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TextInputLayout", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
revealButton.tintColor = Color.grayColor()
warningLabel.textColor = UIColor.red

return view




I want to implement this in this view controller, when i click on next button



import UIKit
import DLRadioButton

class SecureWalletViewController: UIViewController,UITextFieldDelegate

@IBOutlet weak var securityPinStackView: UIStackView!
@IBOutlet weak var securityPin: TextInputLayout!
@IBOutlet weak var confirmSecurityPin: TextInputLayout!

@IBAction func onNextButtonTap(_ sender: Any)



func textInputLayout(at index:Int) -> TextInputLayout
return securityPinStackView.arrangedSubviews[index] as! TextInputLayout











share|improve this question
















I have to make validation on ui text field which used in library called RSFloatInputView.



Here is my xib



import UIKit
import RSFloatInputView

class TextInputLayout: UIView

@IBOutlet weak var revealButton: UIButton!
@IBOutlet weak var warningLabel: UILabel!
@IBOutlet weak var rsFloatingView: RSFloatInputView!
var contentView: UIView?

override init(frame: CGRect)
super.init(frame: frame)
xibSetup()


required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
xibSetup()


func xibSetup()
contentView = loadViewFromNib()
contentView!.frame = bounds
contentView!.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight]
addSubview(contentView!)


func loadViewFromNib() -> UIView!
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TextInputLayout", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
revealButton.tintColor = Color.grayColor()
warningLabel.textColor = UIColor.red

return view




I want to implement this in this view controller, when i click on next button



import UIKit
import DLRadioButton

class SecureWalletViewController: UIViewController,UITextFieldDelegate

@IBOutlet weak var securityPinStackView: UIStackView!
@IBOutlet weak var securityPin: TextInputLayout!
@IBOutlet weak var confirmSecurityPin: TextInputLayout!

@IBAction func onNextButtonTap(_ sender: Any)



func textInputLayout(at index:Int) -> TextInputLayout
return securityPinStackView.arrangedSubviews[index] as! TextInputLayout








ios swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 18 at 7:39









Let's_Create

5212 silver badges19 bronze badges




5212 silver badges19 bronze badges










asked Mar 27 at 7:09









vikas patidarvikas patidar

134 bronze badges




134 bronze badges















  • its for empty validation or else

    – Anbu.Karthik
    Mar 27 at 7:12











  • empty and confirm password

    – vikas patidar
    Mar 27 at 7:21

















  • its for empty validation or else

    – Anbu.Karthik
    Mar 27 at 7:12











  • empty and confirm password

    – vikas patidar
    Mar 27 at 7:21
















its for empty validation or else

– Anbu.Karthik
Mar 27 at 7:12





its for empty validation or else

– Anbu.Karthik
Mar 27 at 7:12













empty and confirm password

– vikas patidar
Mar 27 at 7:21





empty and confirm password

– vikas patidar
Mar 27 at 7:21












4 Answers
4






active

oldest

votes


















4














Use validations for UITextFieldDelegate method like given below:



func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
return true



Or use custom validation function Here






share|improve this answer


































    0














     Iam using this 
    // add func in swift class
    struct validatorConstants
    static let errorMsg = "your error messages"
    static let customMsg = "your error messages"
    static let emailMsg = "your error messages"

    class Validators: NSObject

    //MARK: Validation on any Empty TextField
    func validators(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg,fieldName:String = "") -> Bool
    var error = validatorConstants.errorMsg
    if fieldName.count > 0
    error = fieldName + " is missing"

    if TF1.text?.isEmpty == true
    kAppDelegate.showNotification(text: error)
    return false

    return true


    //MARK: Validation on any Email TextField
    func validatorEmail(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg ,errorMsgEmail:String = validatorConstants.emailMsg,fieldName:String = "Email" ) -> Bool
    var error = validatorConstants.errorMsg
    if fieldName.count > 0
    error = fieldName + " is missing"


    if TF1.text?.isEmpty == true
    kAppDelegate.showNotification(text: error)
    return false

    if TF1.text?.isValidEmail == false
    kAppDelegate.showNotification(text: errorMsgEmail)
    return false

    return true



    // call this func like this
    // your ViewController
    var validator:Validators!
    // In viewdidload
    validator = Validators()
    // call this func on button Action
    guard validator.validators(TF1: txtfied,fieldName: "your txtfield name") == false
    else

    //do something what you want
    return

    // Its works for me hope its works for you





    share|improve this answer
































      0














      I'd recommend to use a UITextField subclass with 2 UI states (regular / invalid) and a validation rule (e.g. not empty / match regex / etc)



      class ValidationTextField: UITextField 

      enum ValidationRule
      case notEmpty
      // case matchRegex(regex: NSRegularExpression)
      // ...


      var validationRule: ValidationRule?

      private(set) var isValid:Bool = true
      didSet
      updateUIForCurrentState()



      // Call this method on the "next" button click
      // (or from the delegate on the textFieldDidEndEditing event for early validation)
      func validate()
      guard let rule = validationRule else
      // nothing to validate
      return;

      switch rule
      case .notEmpty:
      if let length = text?.count
      isValid = length > 0

      else
      isValid = false

      // process other cases (e.g. matchRegex)



      /// Configure your state-specific layout here.
      private func updateUIForCurrentState()
      // Current implementation adds a red border in case of invalid input
      if isValid
      layer.borderWidth = 0
      layer.borderColor = nil

      else
      layer.borderWidth = 2
      layer.borderColor = UIColor.red.cgColor








      share|improve this answer


































        0














        You can use SwiftValidator, It is rule based validator.



        let validator = Validator()

        //Register the fields that you want to validate
        validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])


        @IBAction func signupTapped(sender: AnyObject)
        validator.validate(self)






        share|improve this answer



























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371596%2fwhat-is-better-approach-to-uitextfield-validations-on-ios%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          Use validations for UITextFieldDelegate method like given below:



          func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
          return true



          Or use custom validation function Here






          share|improve this answer































            4














            Use validations for UITextFieldDelegate method like given below:



            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
            return true



            Or use custom validation function Here






            share|improve this answer





























              4












              4








              4







              Use validations for UITextFieldDelegate method like given below:



              func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
              return true



              Or use custom validation function Here






              share|improve this answer















              Use validations for UITextFieldDelegate method like given below:



              func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 
              return true



              Or use custom validation function Here







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jul 18 at 5:41

























              answered Mar 28 at 14:05









              kishan sutharkishan suthar

              602 silver badges6 bronze badges




              602 silver badges6 bronze badges


























                  0














                   Iam using this 
                  // add func in swift class
                  struct validatorConstants
                  static let errorMsg = "your error messages"
                  static let customMsg = "your error messages"
                  static let emailMsg = "your error messages"

                  class Validators: NSObject

                  //MARK: Validation on any Empty TextField
                  func validators(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg,fieldName:String = "") -> Bool
                  var error = validatorConstants.errorMsg
                  if fieldName.count > 0
                  error = fieldName + " is missing"

                  if TF1.text?.isEmpty == true
                  kAppDelegate.showNotification(text: error)
                  return false

                  return true


                  //MARK: Validation on any Email TextField
                  func validatorEmail(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg ,errorMsgEmail:String = validatorConstants.emailMsg,fieldName:String = "Email" ) -> Bool
                  var error = validatorConstants.errorMsg
                  if fieldName.count > 0
                  error = fieldName + " is missing"


                  if TF1.text?.isEmpty == true
                  kAppDelegate.showNotification(text: error)
                  return false

                  if TF1.text?.isValidEmail == false
                  kAppDelegate.showNotification(text: errorMsgEmail)
                  return false

                  return true



                  // call this func like this
                  // your ViewController
                  var validator:Validators!
                  // In viewdidload
                  validator = Validators()
                  // call this func on button Action
                  guard validator.validators(TF1: txtfied,fieldName: "your txtfield name") == false
                  else

                  //do something what you want
                  return

                  // Its works for me hope its works for you





                  share|improve this answer





























                    0














                     Iam using this 
                    // add func in swift class
                    struct validatorConstants
                    static let errorMsg = "your error messages"
                    static let customMsg = "your error messages"
                    static let emailMsg = "your error messages"

                    class Validators: NSObject

                    //MARK: Validation on any Empty TextField
                    func validators(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg,fieldName:String = "") -> Bool
                    var error = validatorConstants.errorMsg
                    if fieldName.count > 0
                    error = fieldName + " is missing"

                    if TF1.text?.isEmpty == true
                    kAppDelegate.showNotification(text: error)
                    return false

                    return true


                    //MARK: Validation on any Email TextField
                    func validatorEmail(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg ,errorMsgEmail:String = validatorConstants.emailMsg,fieldName:String = "Email" ) -> Bool
                    var error = validatorConstants.errorMsg
                    if fieldName.count > 0
                    error = fieldName + " is missing"


                    if TF1.text?.isEmpty == true
                    kAppDelegate.showNotification(text: error)
                    return false

                    if TF1.text?.isValidEmail == false
                    kAppDelegate.showNotification(text: errorMsgEmail)
                    return false

                    return true



                    // call this func like this
                    // your ViewController
                    var validator:Validators!
                    // In viewdidload
                    validator = Validators()
                    // call this func on button Action
                    guard validator.validators(TF1: txtfied,fieldName: "your txtfield name") == false
                    else

                    //do something what you want
                    return

                    // Its works for me hope its works for you





                    share|improve this answer



























                      0












                      0








                      0







                       Iam using this 
                      // add func in swift class
                      struct validatorConstants
                      static let errorMsg = "your error messages"
                      static let customMsg = "your error messages"
                      static let emailMsg = "your error messages"

                      class Validators: NSObject

                      //MARK: Validation on any Empty TextField
                      func validators(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg,fieldName:String = "") -> Bool
                      var error = validatorConstants.errorMsg
                      if fieldName.count > 0
                      error = fieldName + " is missing"

                      if TF1.text?.isEmpty == true
                      kAppDelegate.showNotification(text: error)
                      return false

                      return true


                      //MARK: Validation on any Email TextField
                      func validatorEmail(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg ,errorMsgEmail:String = validatorConstants.emailMsg,fieldName:String = "Email" ) -> Bool
                      var error = validatorConstants.errorMsg
                      if fieldName.count > 0
                      error = fieldName + " is missing"


                      if TF1.text?.isEmpty == true
                      kAppDelegate.showNotification(text: error)
                      return false

                      if TF1.text?.isValidEmail == false
                      kAppDelegate.showNotification(text: errorMsgEmail)
                      return false

                      return true



                      // call this func like this
                      // your ViewController
                      var validator:Validators!
                      // In viewdidload
                      validator = Validators()
                      // call this func on button Action
                      guard validator.validators(TF1: txtfied,fieldName: "your txtfield name") == false
                      else

                      //do something what you want
                      return

                      // Its works for me hope its works for you





                      share|improve this answer













                       Iam using this 
                      // add func in swift class
                      struct validatorConstants
                      static let errorMsg = "your error messages"
                      static let customMsg = "your error messages"
                      static let emailMsg = "your error messages"

                      class Validators: NSObject

                      //MARK: Validation on any Empty TextField
                      func validators(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg,fieldName:String = "") -> Bool
                      var error = validatorConstants.errorMsg
                      if fieldName.count > 0
                      error = fieldName + " is missing"

                      if TF1.text?.isEmpty == true
                      kAppDelegate.showNotification(text: error)
                      return false

                      return true


                      //MARK: Validation on any Email TextField
                      func validatorEmail(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg ,errorMsgEmail:String = validatorConstants.emailMsg,fieldName:String = "Email" ) -> Bool
                      var error = validatorConstants.errorMsg
                      if fieldName.count > 0
                      error = fieldName + " is missing"


                      if TF1.text?.isEmpty == true
                      kAppDelegate.showNotification(text: error)
                      return false

                      if TF1.text?.isValidEmail == false
                      kAppDelegate.showNotification(text: errorMsgEmail)
                      return false

                      return true



                      // call this func like this
                      // your ViewController
                      var validator:Validators!
                      // In viewdidload
                      validator = Validators()
                      // call this func on button Action
                      guard validator.validators(TF1: txtfied,fieldName: "your txtfield name") == false
                      else

                      //do something what you want
                      return

                      // Its works for me hope its works for you






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 27 at 7:56









                      Sukhwinder SinghSukhwinder Singh

                      12211 bronze badges




                      12211 bronze badges
























                          0














                          I'd recommend to use a UITextField subclass with 2 UI states (regular / invalid) and a validation rule (e.g. not empty / match regex / etc)



                          class ValidationTextField: UITextField 

                          enum ValidationRule
                          case notEmpty
                          // case matchRegex(regex: NSRegularExpression)
                          // ...


                          var validationRule: ValidationRule?

                          private(set) var isValid:Bool = true
                          didSet
                          updateUIForCurrentState()



                          // Call this method on the "next" button click
                          // (or from the delegate on the textFieldDidEndEditing event for early validation)
                          func validate()
                          guard let rule = validationRule else
                          // nothing to validate
                          return;

                          switch rule
                          case .notEmpty:
                          if let length = text?.count
                          isValid = length > 0

                          else
                          isValid = false

                          // process other cases (e.g. matchRegex)



                          /// Configure your state-specific layout here.
                          private func updateUIForCurrentState()
                          // Current implementation adds a red border in case of invalid input
                          if isValid
                          layer.borderWidth = 0
                          layer.borderColor = nil

                          else
                          layer.borderWidth = 2
                          layer.borderColor = UIColor.red.cgColor








                          share|improve this answer































                            0














                            I'd recommend to use a UITextField subclass with 2 UI states (regular / invalid) and a validation rule (e.g. not empty / match regex / etc)



                            class ValidationTextField: UITextField 

                            enum ValidationRule
                            case notEmpty
                            // case matchRegex(regex: NSRegularExpression)
                            // ...


                            var validationRule: ValidationRule?

                            private(set) var isValid:Bool = true
                            didSet
                            updateUIForCurrentState()



                            // Call this method on the "next" button click
                            // (or from the delegate on the textFieldDidEndEditing event for early validation)
                            func validate()
                            guard let rule = validationRule else
                            // nothing to validate
                            return;

                            switch rule
                            case .notEmpty:
                            if let length = text?.count
                            isValid = length > 0

                            else
                            isValid = false

                            // process other cases (e.g. matchRegex)



                            /// Configure your state-specific layout here.
                            private func updateUIForCurrentState()
                            // Current implementation adds a red border in case of invalid input
                            if isValid
                            layer.borderWidth = 0
                            layer.borderColor = nil

                            else
                            layer.borderWidth = 2
                            layer.borderColor = UIColor.red.cgColor








                            share|improve this answer





























                              0












                              0








                              0







                              I'd recommend to use a UITextField subclass with 2 UI states (regular / invalid) and a validation rule (e.g. not empty / match regex / etc)



                              class ValidationTextField: UITextField 

                              enum ValidationRule
                              case notEmpty
                              // case matchRegex(regex: NSRegularExpression)
                              // ...


                              var validationRule: ValidationRule?

                              private(set) var isValid:Bool = true
                              didSet
                              updateUIForCurrentState()



                              // Call this method on the "next" button click
                              // (or from the delegate on the textFieldDidEndEditing event for early validation)
                              func validate()
                              guard let rule = validationRule else
                              // nothing to validate
                              return;

                              switch rule
                              case .notEmpty:
                              if let length = text?.count
                              isValid = length > 0

                              else
                              isValid = false

                              // process other cases (e.g. matchRegex)



                              /// Configure your state-specific layout here.
                              private func updateUIForCurrentState()
                              // Current implementation adds a red border in case of invalid input
                              if isValid
                              layer.borderWidth = 0
                              layer.borderColor = nil

                              else
                              layer.borderWidth = 2
                              layer.borderColor = UIColor.red.cgColor








                              share|improve this answer















                              I'd recommend to use a UITextField subclass with 2 UI states (regular / invalid) and a validation rule (e.g. not empty / match regex / etc)



                              class ValidationTextField: UITextField 

                              enum ValidationRule
                              case notEmpty
                              // case matchRegex(regex: NSRegularExpression)
                              // ...


                              var validationRule: ValidationRule?

                              private(set) var isValid:Bool = true
                              didSet
                              updateUIForCurrentState()



                              // Call this method on the "next" button click
                              // (or from the delegate on the textFieldDidEndEditing event for early validation)
                              func validate()
                              guard let rule = validationRule else
                              // nothing to validate
                              return;

                              switch rule
                              case .notEmpty:
                              if let length = text?.count
                              isValid = length > 0

                              else
                              isValid = false

                              // process other cases (e.g. matchRegex)



                              /// Configure your state-specific layout here.
                              private func updateUIForCurrentState()
                              // Current implementation adds a red border in case of invalid input
                              if isValid
                              layer.borderWidth = 0
                              layer.borderColor = nil

                              else
                              layer.borderWidth = 2
                              layer.borderColor = UIColor.red.cgColor









                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 27 at 11:38

























                              answered Mar 27 at 8:35









                              nrxnrx

                              581 silver badge6 bronze badges




                              581 silver badge6 bronze badges
























                                  0














                                  You can use SwiftValidator, It is rule based validator.



                                  let validator = Validator()

                                  //Register the fields that you want to validate
                                  validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])


                                  @IBAction func signupTapped(sender: AnyObject)
                                  validator.validate(self)






                                  share|improve this answer





























                                    0














                                    You can use SwiftValidator, It is rule based validator.



                                    let validator = Validator()

                                    //Register the fields that you want to validate
                                    validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])


                                    @IBAction func signupTapped(sender: AnyObject)
                                    validator.validate(self)






                                    share|improve this answer



























                                      0












                                      0








                                      0







                                      You can use SwiftValidator, It is rule based validator.



                                      let validator = Validator()

                                      //Register the fields that you want to validate
                                      validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])


                                      @IBAction func signupTapped(sender: AnyObject)
                                      validator.validate(self)






                                      share|improve this answer













                                      You can use SwiftValidator, It is rule based validator.



                                      let validator = Validator()

                                      //Register the fields that you want to validate
                                      validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])


                                      @IBAction func signupTapped(sender: AnyObject)
                                      validator.validate(self)







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 27 at 12:12









                                      Toseef KhiljiToseef Khilji

                                      14.4k8 gold badges71 silver badges110 bronze badges




                                      14.4k8 gold badges71 silver badges110 bronze badges






























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371596%2fwhat-is-better-approach-to-uitextfield-validations-on-ios%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현