Validation for input string is CivilID or not?

北城余情 提交于 2019-12-02 11:06:41

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”)
    }
}

Hope it will work for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!