6

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?

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Just use "127.0.0.1" instead "localhost". E.g http://127.0.0.1:13030

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.