更新时间:2023-11-28 22:55:22
首先,允许你的文本字段输入只是数字并给出限制,在你的情况下需要12个字符所以给12个字符限制 - 下面是代码 -
First, allow your textfield input is digit only and give limit as well, in your case 12 character needed so give 12 characters limit - below is the code -
func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
let currentCharacterCount = textField.text?.characters.count
if (range.length + range.location > currentCharacterCount!){
return false
}
let newLength = currentCharacterCount! + string.characters.count - range.length
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return newLength <= 12 && allowedCharacters.isSuperset(of: characterSet)
}
之后只需验证用户的日期是否为出生和输入的出生日期在下面的提交按钮操作中是否正确 -
After that just validate whether user date of birth and entered date of birth is correct or not on submit button action like below -
func submitBtnTapped()
{
//Let say your civicID is like below
let civicID = "113072489656"
var birthDate = String(civicID.characters.prefix(7))
birthDate.remove(at: birthDate.startIndex)
let userBirthDate = "07/24/2013"
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
let date = formatter.date(from: userBirthDate)
print("\(String(describing: date))")
formatter.dateFormat = "yyMMdd"
let actualBirthDate = formatter.string(from: date!)
print(actualBirthDate)
if birthDate == actualBirthDate
{
print("true")
}else {
print("false")
}
}
希望它适合你。