Skip to content

Commit

Permalink
Optimized validation
Browse files Browse the repository at this point in the history
  • Loading branch information
sanzaru committed Oct 25, 2024
1 parent fedf5d0 commit 89b01f5
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
4 changes: 2 additions & 2 deletions Sources/Formify/FormifyDefaultPattern.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
enum FormifyDefaultPattern: String {
case email = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"
case phone = "\\+?([0-9]{1,3})?[-.\\s]?(\\(?[0-9]{1,4}\\)?)?[-.\\s]?[0-9]{1,4}[-.\\s]?[0-9]{1,4}[-.\\s]?[0-9]{0,9}"
case urlWithScheme = "[a-zA-Z]+:\\/\\/{1}[a-zA-Z0-9_\\-.?=&\\/]+"
case urlNoScheme = "[a-zA-Z0-9-_.?=&\\/]+"
case urlWithScheme = "[a-zA-Z0-9]+?:\\/\\/?([a-zA-Z0-9\\-_~+]+(\\.[a-zA-Z0-9\\-_~]+)?+){1}(:\\d+)?(\\/[a-zA-Z0-9\\-_~+]*)*(\\?[a-zA-Z0-9\\-_~=&+\\[\\]@$*,.]*)?(#[a-zA-Z0-9\\-_~+\\[\\]@$*.,]*)?"
case urlNoScheme = "[a-zA-Z0-9-_.?=&\\/+]+"
}
14 changes: 7 additions & 7 deletions Sources/Formify/FormifyField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public struct FormifyField {
public private(set) var isTouched = false
public private(set) var minLength: Int?
public private(set) var maxLength: Int?
public private(set) var pattern: Regex<Substring>?
public private(set) var pattern: String?

private var disableTrimming = false

Expand All @@ -51,15 +51,15 @@ public struct FormifyField {
case .maxLength(let length):
maxLength = length
case .pattern(let regex):
pattern = try? Regex(regex)
pattern = regex
case .email:
pattern = try? Regex(FormifyDefaultPattern.email.rawValue)
pattern = FormifyDefaultPattern.email.rawValue
case .phonenumber:
pattern = try? Regex(FormifyDefaultPattern.phone.rawValue)
pattern = FormifyDefaultPattern.phone.rawValue
case .urlNoScheme:
pattern = try? Regex(FormifyDefaultPattern.urlNoScheme.rawValue)
pattern = FormifyDefaultPattern.urlNoScheme.rawValue
case .urlWithScheme:
pattern = try? Regex(FormifyDefaultPattern.urlWithScheme.rawValue)
pattern = FormifyDefaultPattern.urlWithScheme.rawValue
case .disableTrimming:
disableTrimming = true
}
Expand Down Expand Up @@ -88,7 +88,7 @@ extension FormifyField {
errors.append(.maxLength(value.count))
}

if let pattern, (try? pattern.wholeMatch(in: value)) == nil {
if let pattern, let regex = try? Regex(pattern), (try? regex.wholeMatch(in: value)) == nil {
errors.append(.pattern)
}
}
Expand Down
3 changes: 3 additions & 0 deletions Tests/FormifyTests/FormifyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ import Testing
field.value = "https://example.com/somepath/?foo=bar&foo2=bar2"
#expect(field.isValid)

field.value = "ssh://localhost"
#expect(field.isValid)

field.value = "foobar"
#expect(!field.isValid)
}
Expand Down

0 comments on commit 89b01f5

Please sign in to comment.