1

What I mean by this is I have a birthday field users enter their birthday in. I just want to make sure they are entering legitimate dates like 07-03-2001, not fake dates like 44-88-3333. I already have code in place to makes sure it's the proper format.

 static func isDateValid(value: String?) -> Bool {
      let test = String.trim(value)
      if (String.isNilOrEmpty(test)) {
        return false
      }
      let dateRegEx = "^\\d{2}-\\d{2}-\\d{4}$"
      let dateTest = NSPredicate(format: "SELF MATCHES %@", dateRegEx)
      let result =  dateTest.evaluateWithObject(test)
      return result
    }


   userBirthday = String.trim(self.birthdayTextField!.text)
      if (!String.isDateValid(userBirthday)) {

        showAlertWithTitle("Error".localized(), message: "birthday not valid, please enter in format 07-05-1990".localized() )

        return
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

5 Answers5

1

Using a DatePicker is probably the best approach. However, since that's not what you asked, here's an option in regular expression

let dateRegEx = "^(0[1-9]|[12][0-9]|3[01])[- \\.](0[1-9]|1[012])[- \\.](19|20)\\d\\d$"

year - 1900 to 2099.

DSAjith
  • 362
  • 2
  • 9
0

You can use date formatter it will validate date & returns nil if date is invalid

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"

    if let date = dateFormatter.dateFromString("25-34-2014")
    {
        print("true date:\(date)")
    }
    else
    {
        print("wrong date")
    }
Mohamed Mostafa
  • 1,057
  • 7
  • 12
0

You can use the default NSDateFormatter() function, and use .dateFormat to set the format to that. Use "dd" for day, "MM" for month, and "yyyy" for year. Then use .dateFromString(stringThatContainsTheDate) inside an if statement to test if it is in it.

Example:

 let date = theTextField.text
 let dateFormat = NSDateFormatter()
 dateFormat.dateFormat = "dd-MM-yyyy"

if let date = dateFormatr.dateFromString(date)
{
    print("This Date Is formatted correctly")
}
Matthew Bergwall
  • 310
  • 1
  • 10
0

I took a different approach than what the others used, by using a date picker which gives you the ability through minimumDate and maximumDate to specify limits. In my opinion, this provides a much cleaner interface to the user, rather than forcing them to type in dates that may in fact be wrong.

import UIKit

class ViewController: UIViewController {
    // Connection to textfield in the storyboard that user uses to interact with date picker
    @IBOutlet weak var dateField: UITextField!
    @IBOutlet weak var pickerView: UIDatePicker!

    // This particular max date is one day in the future. You can modify it to suit your needs
    var maximumDate: NSDate {
        return NSCalendar.currentCalendar()
            .dateByAddingUnit(
                .Day,
                value: 1,
                toDate: NSDate(),
                options: []
            )!
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupPicker()
    }

    func setupPicker() {
        // This line replaces the standard keyboard with the date picker
        dateField.inputView = pickerView
        // This line prevents a crash related to using the date picker in place of the keyboard
        pickerView.removeFromSuperview()
        pickerView.minimumDate = NSDate()
        pickerView.maximumDate = maximumDate
    }

    // Connect an action from the datepicker in your storyboard file to here
    @IBAction func dateSelected(sender: UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        dateField.text = dateFormatter.stringFromDate(sender.date)
        dateField.resignFirstResponder()
    }
}

And how it looks in action.

enter image description here

If the date is not supported, it will then appear in light gray rather than black.

CodeBender
  • 35,668
  • 12
  • 125
  • 132
0

Simple. Just set pickerView.maximumDate equal to the max date you want.