尝试textField获得信用卡的到期日期,下面的代码正常工作只是想改变行为,目前当您从第三个数字/字符输入时,将添加为到期格式。如果我想在用户输入第二个数字后添加/字符怎么办,例如如果用户输入 01 直接插入分隔符
open func reformatAsExpiration(_ textField: UITextField) {
guard let string = textField.text else { return }
let expirationString = String(ccrow.expirationSeparator)
let cleanString = string.replacingOccurrences(of: expirationString, with: "", options: .literal, range: nil)
if cleanString.length >= 3 {
let monthString = cleanString[Range(0...1)]
var yearString: String
if cleanString.length == 3 {
yearString = cleanString[2]
} else {
yearString = cleanString[Range(2...3)]
}
textField.text = monthString + expirationString + yearString
} else {
textField.text = cleanString
}
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特5:
这是验证输入的月份和年份的解决方案
使用 TextField 委托方法 shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let r = Range(range, in: oldText) else {
return true
}
let updatedText = oldText.replacingCharacters(in: r, with: string)
if string == "" {
if updatedText.count == 2 {
textField.text = "\(updatedText.prefix(1))"
return false
}
} else if updatedText.count == 1 {
if updatedText > "1" {
return false
}
} else if updatedText.count == 2 {
if updatedText <= "12" { //Prevent user to not enter month more than 12
textField.text = "\(updatedText)/" //This will add "/" when user enters 2nd digit of month
}
return false
} else if updatedText.count == 5 {
self.expDateValidation(dateStr: updatedText)
} else if updatedText.count > 5 {
return false
}
return true
}
Run Code Online (Sandbox Code Playgroud)
以下函数中的验证逻辑
func expDateValidation(dateStr:String) {
let currentYear = Calendar.current.component(.year, from: Date()) % 100 // This will give you current year (i.e. if 2019 then it will be 19)
let currentMonth = Calendar.current.component(.month, from: Date()) // This will give you current month (i.e if June then it will be 6)
let enteredYear = Int(dateStr.suffix(2)) ?? 0 // get last two digit from entered string as year
let enteredMonth = Int(dateStr.prefix(2)) ?? 0 // get first two digit from entered string as month
print(dateStr) // This is MM/YY Entered by user
if enteredYear > currentYear {
if (1 ... 12).contains(enteredMonth) {
print("Entered Date Is Right")
} else {
print("Entered Date Is Wrong")
}
} else if currentYear == enteredYear {
if enteredMonth >= currentMonth {
if (1 ... 12).contains(enteredMonth) {
print("Entered Date Is Right")
} else {
print("Entered Date Is Wrong")
}
} else {
print("Entered Date Is Wrong")
}
} else {
print("Entered Date Is Wrong")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4804 次 |
| 最近记录: |