8

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 Answers 3

14

Just to complete this :

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

[Required]
[Url]
public string Website { get; set; }
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to make it optional?
In .NET 8 (maybe older versions too?) it's optional for string?.
13

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

Comments

1

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.

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.