Skip to content

Commit

Permalink
Fix address bar queries when doing math expressions (#952)
Browse files Browse the repository at this point in the history
  • Loading branch information
jotaemepereira authored Aug 25, 2024
1 parent 925b3e4 commit c92b865
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Sources/Common/Extensions/StringExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ extension RegEx {
static let hostName = regex("^(((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)*[A-Za-z0-9-]{2,63})$", .caseInsensitive)

static let email = regex(#"[^\s]+@[^\s]+\.[^\s]+"#)

static let mathExpression = regex(#"^[\s$]*([\d]+(\.[\d]+)?|\\.[\d]+)([\s]*[+\-*/][\s]*([\d]+(\.[\d]+)?|\\.[\d]+))*[\s$]*$"#)
}

// Use this instead of NSLocalizedString for strings that are not supposed to be translated
Expand Down Expand Up @@ -362,7 +364,11 @@ public extension String {
// MARK: Host name validation

var isValidHost: Bool {
return isValidHostname || isValidIpHost
return (isValidHostname || isValidIpHost) && !isMathFormula
}

private var isMathFormula: Bool {
return matches(.mathExpression)
}

var isValidHostname: Bool {
Expand Down
34 changes: 34 additions & 0 deletions Tests/CommonTests/Extensions/StringExtensionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -336,4 +336,38 @@ final class StringExtensionTests: XCTestCase {

}

func testWhenStringIsValidHost_thenValidHostIsTrue() {
let validHostnames = [
"example.com",
"subdomain.example.com",
"my-host123",
"localhost",
"192.168.1.1", // Valid IP address
"2001:0db8:85a3:0000:0000:8a2e:0370:7334" // Valid IPv6 address
]

for hostname in validHostnames {
XCTAssertTrue(hostname.isValidHost, "\(hostname) should be a valid host")
}
}

func testWhenStringIsInvalidHost_thenValidHostIsFalse() {
let invalidHostnames = [
"invalid_hostname", // Invalid character
"-example.com", // Starts with a hyphen
"example-.com", // Ends with a hyphen
"example..com", // Consecutive dots
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.com", // Too long
"example.com.", // Ends with a dot
"3 + 5 * (2 - 1)", // Mathematical expression
"16385-12228.72", // Other mathetmatical expression
"[email protected]", // Invalid character
"2001:0db8:85a3:0000:0000:8a2e:0370:7334:1234" // Invalid IPv6 address
]

for hostname in invalidHostnames {
XCTAssertFalse(hostname.isValidHost, "\(hostname) should NOT be a valid host")
}
}

}

0 comments on commit c92b865

Please sign in to comment.