In our ASP.MVC project we are using DataAnnotations attributes for validation. One of the fields should contains Url and it is marked with [Url] attribute. But if I put http://localhost:13030 into the field value it isn't passing the validation.
Is there any way to use the attribute to define localhost as a valid target?
UrlAttribute validates against the RegEx shown in the source code here: https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/UrlAttribute.cs#L46.
http://localhost doesn't match due to its lack of a ..
See this answer for other options: How I can validate urls in C# for localhost.
EDIT: According to the source code, you could add dataAnnotations:dataTypeAttribute:disableRegEx to your AppSettings and set its value to true. This would cause the UrlAttribute validation process to only check that it begins with http://, https:// or ftp://. See Line 33 of the same source file for that.
To expand upon Kirk Larkin's answer: The "dataAnnotations:dataTypeAttribute:disableRegEx" app setting is only available since .NET Framework 4.6.1, according to dotnet pull request #668 (re-add ASPNET472CompatDoc).
I also checked by downloading the .NET Framework 4.6 (58 MB .zip) and 4.6.1 RTM (59 MB .zip) source and running the following git diff command.
git diff D:/src/dotnet46/Source/ndp/fx/src/xsp/system/DataAnnotations/DataAnnotations/UrlAttribute.cs D:/src/dotnet461RTM/Source/ndp/fx/src/xsp/system/DataAnnotations/DataAnnotations/UrlAttribute.cs
Indeed, the new-as-of-4.6.1 internal static class AppSettings is what reads the new-as-of-4.6.1 app setting.
And ... My point in adding this answer is that I am out of luck on net452.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With