输入字符串的验证是否为CivilID? [英] Validation for input string is CivilID or not?

查看:81
本文介绍了输入字符串的验证是否为CivilID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITextfield,格式如下。这是我们通常在海湾国家看到的民事身份证。所以我需要在Swift的UITextfield中验证相同的内容。

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.

民用ID格式 - NYYMMDDNNNNN其中N是数字,YY是出生年份的最后两位数字,MM出生月份, DD出生日期..

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

请告诉我如何对此进行验证。我目前正在使用目标c代码验证出生日期:

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]; 

但是我的格式如何对swift中需要NYYMMDDNNNNN的格式做同样的事情。

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

推荐答案

首先,允许你的文本字段输入只是数字并给出限制,在你的情况下需要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")
    }
}

希望它适合你。

这篇关于输入字符串的验证是否为CivilID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆