Search code examples
c#asp.net-mvcvalidationdata-annotations

Url validation attribute marks `localhost` as invalid Url


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?


Solution

  • 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.