mvc4 url validation

Amila picture Amila · Mar 6, 2013 · Viewed 30.5k times · Source

I'm writing this question here after trying to find an answer for two days.

basically here's what's going on.

I have a property in the viewmodel as follows

[Required(ErrorMessage = "Required Field")]
[Url(ErrorMessage="Please enter a valid url")]
[DisplayName("Website")]
public string web { get; set; }

in the view, I have this

@Html.EditorFor(model => model.web, new { AutoCompleteType = "Disabled", autocomplete = "off" })

now the problem lies in how the input text for this field is validated in the client side. the field must have the protocol prefix at all times, otherwise it becomes invalid.

what is the best way I can fix this issue?

Many Thanks

Answer

Erik Schierboom picture Erik Schierboom · Mar 6, 2013

You can do this using the DataAnnotationsExtensions library. They have an UrlAttribute that you can configure to only validate when a protocol is specified. This attribute also supplies client-side validation. You can see an example of this behavior here: http://dataannotationsextensions.org/Url/Create

You can use this attribute as follows:

using System.ComponentModel.DataAnnotations;

namespace DataAnnotationsExtensions.Core
{
    public class UrlEntity
    {
        [Url]
        [Required]
        public string Url { get; set; }

        [Url(UrlOptions.OptionalProtocol)]
        [Required]
        public string UrlWithoutProtocolRequired { get; set; }

        [Url(UrlOptions.DisallowProtocol)]
        [Required]
        public string UrlDisallowProtocol { get; set; }
    }
}

For your purposes, the first option suffices.

The package of this library (with ASP.NET MVC support included) can be found on NuGet: Install-Package DataAnnotationsExtensions.MVC3

Note: this also works fine with ASP.NET MVC 4