ValidatorKit is a flexible and extensible validation library for Swift, designed to simplify form validation in iOS apps.
将以下内容添加到您的 Package.swift
文件
dependencies: [
.package(url: "https://github.com/Alhiane/ValidatorKit.git", from: "1.0.0-beta")
]
import ValidatorKit
// Setup your schema
let schema = ValidationSchema()
.field("username").required() // Field must be present and not empty
.field("email").required().email() // Field must be a valid email format
.field("gender").requiredIf(username == "johndoe") // Required if username is "johndoe"
.field("age").required().greaterThan(18) // Must be greater than 18
.field("amount").numeric().min(100.08) // Must be a number and at least 100.08
.field("password").required().custom(message: "Password must be at least 8 characters") { value in
guard let password = value as? String, password.count >= 8 else {
return false
}
return true
}
.field("url").required().URL() // Must be a valid URL
.field("dateOfBirth").required().date() // Must be a valid date
.field("file").required().MIMETypes(["image/jpeg", "image/png"]) // Must be a valid file type
.field("hobbies").inArray(["coding", "reading", "traveling"]) // Must be one of the allowed values
.field("score").numeric().min(0).max(100) // Must be a number between 0 and 100
.field("customField").pattern("^[A-Z]{3}-\\d{3}$") // Must match the pattern "XXX-123"
.ready()
// Example data for validation
let validData: [String: Any] = [
"username": "alhiane",
"email": "aie@aie.aie",
"gender": "male",
"age": 25,
"amount": "150.00",
"password": "securePassword123",
"url": "https://example.com",
"dateOfBirth": Date(),
"file": "image/jpeg",
"hobbies": "coding",
"score": 85,
"customField": "ABC-123"
]
let invalidData: [String: Any] = [
"username": "",
"email": "not-an-email",
"gender": "",
"age": 16,
"amount": "50.00",
"password": "short",
"url": "invalid-url",
"dateOfBirth": "not-a-date",
"file": "text/plain",
"hobbies": "sports",
"score": 150,
"customField": "invalid"
]
// Validate function
let validResult = schema.validate(validData)
let invalidResult = schema.validate(invalidData)
// Check validation results
print(validResult.isValid) // true
print(invalidResult.isValid) // false
// Access validation errors
print(invalidResult.errors) // Display all errors
规则名称 | 描述 |
---|---|
custom() |
允许使用消息进行自定义验证逻辑。 |
email() |
验证字段是否包含有效的电子邮件格式。 |
min(value) |
确保该值大于或等于指定的最小值。 |
max(value) |
确保该值小于或等于指定的最大值。 |
numeric() |
验证字段是否包含数字值。 |
date() |
验证字段是否包含有效的日期。 |
range(range) |
验证该值是否在指定的范围内。 |
pattern(pattern) |
验证该值是否与指定的正则表达式模式匹配。 |
URL() |
验证字段是否包含有效的 URL。 |
inArray(array) |
验证该值是否为数组中允许的值之一。 |
requiredIf(condition) |
根据指定的条件使字段成为必需字段。 |
required() |
确保字段存在且不为空。 |
greaterThan(value) |
验证该值是否大于指定的值。 |
leassThan(value) |
验证该值是否小于指定的值。 |
MIMETypes(types) |
验证文件类型是否与允许的 MIME 类型之一匹配。 |