7
votes

I'm using ASP.NET MVC3 and trying to validate an URL field using DataAnnotationsExtensions.

It's almost what I need. However, it forces the user to add "http://" at the beggining of the URL string, if not, it will show the following validation message:

The URL field is not a valid fully-qualified http, https, or ftp URL.

In the Data Annotations Extensions URL demo page it shows an additional validator UrlWithoutProtocolRequired, but I cannot find it anywhere.

How can I use this validator, or how can I easily validate the URL without the "http://" part?

3

3 Answers

12
votes

The protocol-less option for DataAnnotationsExtensions is available in the source code but is considered beta or "vNext" and hasn't been released as part of the NuGet package. So if you download the source and compile you'll see the [Url] attribute has an overload [Url(requireProtocol: false)]. You can see this in the latest UrlAttribute.cs file (UrlArribute.cs). Also if you look in the DataAnnotationsExtensions wiki you'll see this feature is scheduled to be released soon (I'm thinking in the next week or two for an official next release).

9
votes

Just to complete this :

Since MVC3 now we can use [URL] validation attribute.

[Required]
[Url]
public string Website { get; set; }
1
votes

I could not find a built in attribute to match a URL and accept the protocol as optional.

So instead, I used the following RegularExpression validator:

public class MediaModel
{
    public long MediaId { get; set; }
    [StringLength(60)]
    [RegularExpression(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", ErrorMessage = "Not a valid website URL")]
    public string Website { get; set; }
    [DisplayName("YouTube Video")]
    [StringLength(200)]
    [RegularExpression(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", ErrorMessage = "Not a valid YouTube video")]
    public string YouTubeVideo { get; set; }
}

I copied the Regular expression from here, it is a good one.