19

can some one tell me how can i validate a url like http://www.abc.com

Yannick Blondeau
  • 9,465
  • 8
  • 52
  • 74
maztt
  • 12,278
  • 21
  • 78
  • 153

10 Answers10

40

Let the System.Uri do the heavy lifting for you, instead of a RegEx:

public class UrlAttribute : ValidationAttribute
{
    public UrlAttribute()
    {
    }

    public override bool IsValid(object value)
    {
        var text = value as string;
        Uri uri;

        return (!string.IsNullOrWhiteSpace(text) && Uri.TryCreate(text, UriKind.Absolute, out uri ));
    }
}
Dan Marshall
  • 644
  • 1
  • 6
  • 9
28

Now (at least form ASP.NET MVC 5) you can use UrlAttribute and that includes server and client validation:

[Url]
public string WebSiteUrl { get; set; }
Sebastián Rojas
  • 2,776
  • 1
  • 25
  • 34
10

If you are using MVC3 RTM, you can just use [URL] validation attribute.

Refer http://weblogs.asp.net/imranbaloch/archive/2011/02/05/new-validation-attributes-in-asp-net-mvc-3-future.aspx

HashCoder
  • 946
  • 1
  • 13
  • 32
5

If, by the title of your post, you want to use MVC DataAnnotations to validate a url string, you can write a custom validator:

public class UrlAttribute : ValidationAttribute
{
    public UrlAttribute() { }

    public override bool IsValid(object value)
    {
        //may want more here for https, etc
        Regex regex = new Regex(@"(http://)?(www\.)?\w+\.(com|net|edu|org)");

        if (value == null) return false;

        if (!regex.IsMatch(value.ToString())) return false;

        return true;
    }
}

Phil Haack has a good tutorial that goes beyond this and also includes adding code to validate on the client side via jQuery: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

Michael Finger
  • 1,110
  • 9
  • 9
5

What about using URL attribute, like:

public class ProveedorMetadata
{
    [Url()]
    [Display(Name = "Web Site")]
    public string SitioWeb { get; set; }
}
odelgadillo
  • 185
  • 2
  • 6
  • I thought so, too. That only works for HTTP, HTTPS, and FTP. If you want other URLs - like mailto or file! - you're screwed, which is normal for Microsoft. – Suncat2000 Apr 14 '21 at 19:15
2

Here is proper validation attribute code used in prod system:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class UriValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null || value.ToString() == string.Empty)
        {
            return true;
        }

        try
        {
            Uri result;
            if (Uri.TryCreate(value.ToString(), UriKind.RelativeOrAbsolute, out result))
            {
                if (result.Scheme.StartsWith("http") || result.Scheme.StartsWith("https"))
                {
                    return true;
                }
            }
        }
        catch
        {
            return false;
        }

        return false;
    }
}
sandeep talabathula
  • 3,238
  • 3
  • 29
  • 38
0

I use this regular expression for Internal or external URLS on my site.

((?:https?\:\/\/|\/.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)
Luis Tellez
  • 2,785
  • 1
  • 20
  • 28
0

Use a regular expression data annotation, and use a regex like:

http://www\.\w+\.(com|net|edu|org)

Depending on what you need to validate; are you requiring http: or are you requiring www.? So that could change the regular expression, if optional, to:

(http://)?(www\.)?\w+\.(com|net|edu|org)
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

Since .NET Framework 4.5 all the way thru to .NET 7+, you can use the Url attribute on the model's property.

[Url]
public string MyUrl { get; set; }

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.urlattribute?view=net-6.0

Dave Black
  • 7,305
  • 2
  • 52
  • 41
-1

Uri.IsWellFormedUriString checks that the URL format is correct and does not require escaping.

/// <summary>
/// Ensures the property is a valid URL.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class ValidateUrlAttribute :  ValidationAttribute
{
    public ValidateUrlAttribute()
    {
    }

    public override bool IsValid(object value)
    {
        // Do not validate missing URLs - people can use [Required] for that.
        string text = (value as string) ?? "";

        if (text == "")
            return true;

        return Uri.IsWellFormedUriString(text, UriKind.Absolute);
    }
}