Validation for input string is CivilID or not?

2019-03-05 06:34发布

I have got a UITextfield with the following format . It is a Civil ID which we usually get to see in Gulf Countries. So I need to validate the same in my UITextfield in Swift.

Civil ID format - NYYMMDDNNNNN where N a digit, YY last two digits of birth year, MM birth month, DD birth date..

Please tell me how to do validation for this. I am currently validating the Date of Birth using the objective c code:

NSString *dateFromTextfield = @"07/24/2013";

   // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];// here set format which you want...
    NSDate *date = [dateFormat dateFromString:dateFromTextfield]; 

But how to do the same for my format requiring "NYYMMDDNNNNN" in swift.

1条回答
\"骚年 ilove
2楼-- · 2019-03-05 07:25

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.

查看更多
登录 后发表回答