EGFormValidator
用 Swift 4.2 编写的简单表单验证库。
特性
-
内置验证器
- 必需
- 最大长度(目前仅支持
UITextField
)。使用 Storyboard 来设置。 - 最小长度
- 纯数字
- 等于(一个输入值等于另一个输入值)
- 字母数字
- 正则表达式
-
自定义验证器
-
验证任何
UITextField
或UITextView
,或者你可以创建自己的可验证输入字段 -
为高亮显示无效输入字段添加自定义样式
-
条件验证
演示
pod try EGFormValidator
需求
- iOS 8.0+
- Xcode 8.2+
- Swift 3.0+
安装
在项目中使用EGFormValidator的推荐方法是通过CocoaPods包管理器,因为它提供了灵活的依赖管理以及简单易行的安装过程。
CocoaPods
如果未安装,请安装CocoaPods
$ [sudo] gem install cocoapods
$ pod setup
前往您的Xcode项目目录,创建并编辑Podfile文件,并添加EGFormValidator到相应的TargetName
$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
target 'TargetName' do
pod 'EGFormValidator'
end
将安装包添加到您的项目中
$ pod install
从.xcworkspace文件(而不是常规的项目文件)打开Xcode项目
$ open MyProject.xcworkspace
现在您可以在文件中导入 EGFormValidator
框架。
用法
基本
1. 扩展ValidatorViewController
class MyViewController: ValidatorViewController {
}
2. 将验证器放置在viewDidLoad中,按照它们必须执行的顺序。
override func viewDidLoad() {
super.viewDidLoad()
//
// Place your validation code here
//
// Mandatory validation
self.addValidatorMandatory(toControl: self.fullnameTextfield,
errorPlaceholder: self.fullnameErrorLabel,
errorMessage: "This field is required")
// Minlength
self.addValidatorMinLength(toControl: self.fullnameTextfield,
errorPlaceholder: self.fullnameErrorLabel,
errorMessage: "Enter at least %d characters",
minLength: 8)
// Email
self.addValidatorEmail(toControl: self.emailTextField,
errorPlaceholder: self.emailErrorLabel,
errorMessage: "Email is invalid")
// Digits Only
self.addValidatorDigitsOnly(toControl: self.postalCodeTextfield,
errorPlaceholder: self.postalCodeErrorLabel,
errorMessage: "Postal code must contain only digits")
// Equalty
self.addValidatorEqualTo(toControl: self.passwordConfirmationTextField,
errorPlaceholder: self.passwordConfirmationErrorLabel,
errorMessage: "Passwords don't match",
compareWithControl: self.passwordTextField)
// AlphaNumeric
self.addValidatorAlphaNumeric(toControl: self.alphaNumericTextField,
errorPlaceholder: self.aphaNumericErrorLabel,
errorMessage: "Only letters and digits are allowed")
}
3. 执行self.validate()
来验证您的表单
if self.validate() {
// form is valid
}
添加样式:高亮有效的和非法的输入
只需实现 Validatable
协议的可选方法 setValidation
。例如
import UIKit
class SuperTextField: UITextField, Validatable {
// textfield initializatin
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
layer.cornerRadius = 6
layer.borderWidth = 2
setNormalBorderColor()
}
func setNormalBorderColor() {
layer.borderColor = UIColor(red: 244.0/255.0, green: 177.0/255.0, blue: 61.0/255.0, alpha: 1.0).cgColor
textColor = UIColor(red: 86.0/255.0, green: 86.0/255.0, blue: 86.0/255.0, alpha: 1.0)
backgroundColor = .white
}
//
// MARK: - Validatable protocol implementation
func setValidation(state: ValidatableControlState) {
if state == .error {
layer.borderColor = UIColor(red: 230.0/255.0, green: 47.0/255.0, blue: 44.0/255.0, alpha: 1.0).cgColor
textColor = .white
backgroundColor = UIColor(red: 239.0/255.0, green: 158.0/255.0, blue: 158.0/255.0, alpha: 1.0)
} else {
setNormalBorderColor()
}
}
}
自定义验证器
创建一个验证器
let myNewShinyValidator = Validator(control: control, // any class that conforms Validatable protocol: use UITextField, UITextView or create your own (for more, see 'Custom input fields' section)
predicate: AlphaNumericValidatorFunction // a function that complies (Any?, [Any?]) -> Bool
predicateParameters: [], // Pass as many extra parametes as you want
errorPlaceholder: errorPlaceholderLabel, // anything that conforms ValidationErrorDisplayable protocol: use UILabel or create your own (for more, see 'Custom error placeholders' section)
errorMessage: "This input is invalid") // Error message
创建一个谓词
func AlphaNumericValidatorFunction(value: Any?, params: [Any?]) -> Bool {
let badCharacters = NSCharacterSet.alphanumerics.inverted
if let myString = value as? String, myString.rangeOfCharacter(from: badCharacters) == nil {
return true
}
return false
}
使用 self.add(validator: myNewShinyValidator)
添加您的验证器。
自定义输入字段
只需实现 Validatable
协议的必需方法 getValue
。例如
import UIKit
extension MyDropDown: Validatable {
// MARK - Validatable Protocol Implementation
func getValue() -> Any? {
return self.text // it must return a value that will be validated
}
}
自定义错误占位符
实现 ValidationErrorDisplayable
协议的必需方法 setErrorMessage
。例如
import UIKit
extension SomeCustomView: ValidationErrorDisplayable {
// MARK - Validation Error Displayable protocol implementation
func setErrorMessage(errorMessage: String?) {
// do stuff to show an error message
self.errorLabel.text = errorMessage
}
}
条件验证
您可以根据需要定义是否应用特定的验证器。简单地在验证器中添加一个条件。
对于自定义验证器
self.add(validator: aValidator, condition: { () -> Bool {
return false // return true if you want to apply this validator and false otherwise
})
对于核心验证器
// in this case it's digit-only validator, the same syntax is applied to the others
self.addValidatorDigitsOnly(toControl: self.myTextfield,
errorPlaceholder: self.myTextfieldErrorLabel,
errorMessage: "Digits only please") { () -> Bool {
return false // return true if you want to apply this validator and false otherwise
}
假设您有两个字段:座机和手机。并且您想要用户至少填写其中之一。
self.addValidatorMandatory(toControl: self.cellphoneTextfield,
errorPlaceholder: self.cellphoneErrorLabel,
errorMessage: "Please enter your home phone number or your cellphone") { [unowned self] () -> Bool in
if let landline = self.landlineTextfield.getValue() as? String, landline.characters.count > 0 {
return false
}
return true
}
self.addValidatorMandatory(toControl: self.landlineTextfield,
errorPlaceholder: self.landlineErrorLabel,
errorMessage: "Please enter your home phone number or your cellphone") { [unowned self] () -> Bool in
if let cellphone = self.cellphoneTextfield.getValue() as? String, cellphone.characters.count > 0 {
return false
}
return true
}