From fab5e41f2b34479c2bbdbcaf2f6c32ed39d06a81 Mon Sep 17 00:00:00 2001 From: Patrick Date: Thu, 7 Dec 2023 20:09:02 +0100 Subject: [PATCH] Improve URL pattern matching (#2248) * Improve URL pattern matching * Add more url matching tests --- Source/Validations/RuleRegExp.swift | 2 +- Tests/ValidationsTests.swift | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Source/Validations/RuleRegExp.swift b/Source/Validations/RuleRegExp.swift index 601ecd05..427e62b7 100644 --- a/Source/Validations/RuleRegExp.swift +++ b/Source/Validations/RuleRegExp.swift @@ -26,7 +26,7 @@ import Foundation public enum RegExprPattern: String { case EmailAddress = "^[_A-Za-z0-9-+!?#$%'`*/=~^{}|]+(\\.[_A-Za-z0-9-+!?#$%'`*/=~^{}|]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-zā€Œā€‹]{2,})$" - case URL = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+([/?#]\\S*)?" + case URL = "^(?:(?:http|https)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$" case ContainsNumber = ".*\\d.*" case ContainsCapital = "^.*?[A-Z].*?$" case ContainsLowercase = "^.*?[a-z].*?$" diff --git a/Tests/ValidationsTests.swift b/Tests/ValidationsTests.swift index 9acdd267..29061e40 100644 --- a/Tests/ValidationsTests.swift +++ b/Tests/ValidationsTests.swift @@ -167,9 +167,14 @@ class ValidationsTests: XCTestCase { XCTAssertNil(urlRule.isValid(value: nil)) XCTAssertNil(urlRule.isValid(value: URL(string: ""))) XCTAssertNil(urlRule.isValid(value: URL(string: "http://example.com"))) + XCTAssertNil(urlRule.isValid(value: URL(string: "http://to.co"))) XCTAssertNil(urlRule.isValid(value: URL(string: "https://example.com/path/to/file.ext?key=value#location"))) - + XCTAssertNil(urlRule.isValid(value: URL(string: "https://example.com:8080/path/to/file.ext?key=value#location"))) + XCTAssertNil(urlRule.isValid(value: URL(string: "https://localhost"))) + XCTAssertNil(urlRule.isValid(value: URL(string: "https://localhost:8080"))) + XCTAssertNotNil(urlRule.isValid(value: URL(string: "example.com"))) + XCTAssertNotNil(urlRule.isValid(value: URL(string: "www.example.com"))) XCTAssertNotNil(urlRule.isValid(value: URL(string: "http://"))) } }