How to handle Date in TextField?

Hi,

How to handle Date in TextField with all validations?

suppose if my date format is DD/MM/YYYY HH:mm,

and when i type the date ,for example 10

it should add /

and when i type month ,for example 10/12

it should add /

and when i type year ,for example 10/12/2019

it should add a space

and when i type the hour,for example 10/12/2019 10

it should add a colon

and then i can type the minutes like 10/12/2019 10:10


My code Snippet:

In textfield delegate method , shouldChangeCharactersIn ,


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



if textField.text?.count == 1 {

textField.placeholder = "DD/MM/YYYY HH:mm"

}


if (textField.text?.count == 2) || (textField.text?.count == 5) {

//Handle backspace being pressed

if !(string == "") {

txtValue.text = textField.text! + "/"

}

}else if (textField.text?.count == 10) {

if !(string == "") {

txtValue.text = textField.text! + " "

}

}else if (textField.text?.count == 13) {

if !(string == "") {

txtValue.text = textField.text! + ":"

}

}

return !(textField.text!.count > 15 && (string.count) > range.length)

}


The problem is ,

when backspace tapped from inbetween the date in the textfield,it should validate the date.How to handle this?


below gif image shows what is required.

I didn't know that capability of Date picker. Impressive.


I tested on calendar and effectively, dates betwwen Thurs Oct 4, 1582 and Fri Oct 14, 1582 are refused.

But dateFormatter is my friend, as it manages it as well.


Entering 05/10/1582, date displayed by dateFormatter is

Friday, Oct 15, 1582 @10:10



Which allows to write an adhoc message as:

Friday, Oct 15, 1582 @10:10

Proleptic Gregorian date

How to handle Date in TextField?
 
 
Q