Skip to content

Commit cc77763

Browse files
MaximysMaksim Golev
andauthored
Add support of System.Uri to UrlAttribute (#114992)
* refactor(#71008): Apply some modern C# syntax to "UrlAttribute". * feat(#71008): Add Uri support. --------- Co-authored-by: Maksim Golev <mgolev@htc-cs.ru>
1 parent c6ad0a8 commit cc77763

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UrlAttribute.cs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,29 @@ public UrlAttribute()
1717

1818
public override bool IsValid(object? value)
1919
{
20-
if (value == null)
20+
switch (value)
2121
{
22-
return true;
22+
case Uri valueAsUri:
23+
{
24+
return valueAsUri.Scheme == Uri.UriSchemeHttp
25+
|| valueAsUri.Scheme == Uri.UriSchemeHttps
26+
|| valueAsUri.Scheme == Uri.UriSchemeFtp;
27+
}
28+
case string valueAsString:
29+
{
30+
return valueAsString.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
31+
|| valueAsString.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
32+
|| valueAsString.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase);
33+
}
34+
case null:
35+
{
36+
return true;
37+
}
38+
default:
39+
{
40+
return false;
41+
}
2342
}
24-
25-
return value is string valueAsString &&
26-
(valueAsString.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
27-
|| valueAsString.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
28-
|| valueAsString.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase));
2943
}
3044
}
3145
}

src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/UrlAttributeTests.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,18 @@ protected override IEnumerable<TestCase> ValidValues()
1414
yield return new TestCase(new UrlAttribute(), "http://foo.bar");
1515
yield return new TestCase(new UrlAttribute(), "https://foo.bar");
1616
yield return new TestCase(new UrlAttribute(), "ftp://foo.bar");
17+
yield return new TestCase(new UrlAttribute(), new Uri("http://foo.bar"));
18+
yield return new TestCase(new UrlAttribute(), new Uri("https://foo.bar"));
19+
yield return new TestCase(new UrlAttribute(), new Uri("ftp://foo.bar"));
1720
}
1821

1922
protected override IEnumerable<TestCase> InvalidValues()
2023
{
2124
yield return new TestCase(new UrlAttribute(), "file:///foo.bar");
2225
yield return new TestCase(new UrlAttribute(), "foo.png");
2326
yield return new TestCase(new UrlAttribute(), new object());
27+
yield return new TestCase(new UrlAttribute(), new Uri("file:///foo.bar"));
28+
yield return new TestCase(new UrlAttribute(), new Uri("//foo.png"));
2429
}
2530

2631
[Fact]

0 commit comments

Comments
 (0)