Skip to content

Commit

Permalink
Add math check for math expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
jotaemepereira committed Aug 21, 2024
1 parent 2efee14 commit a486a77
Show file tree
Hide file tree
Showing 2 changed files with 42 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
}

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

var isValidHostname: Bool {
Expand Down
35 changes: 35 additions & 0 deletions Tests/CommonTests/Extensions/StringExtensionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -336,4 +336,39 @@ 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
"192.168.1.256", // Invalid IP address
"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")

Check failure on line 370 in Tests/CommonTests/Extensions/StringExtensionTests.swift

View workflow job for this annotation

GitHub Actions / Run unit tests (macOS)

testWhenStringIsInvalidHost_thenValidHostIsFalse, XCTAssertFalse failed - 192.168.1.256 should NOT be a valid host
}
}

}

0 comments on commit a486a77

Please sign in to comment.