Dan*_*all 38

让System.Uri为您做繁重的工作,而不是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 ));
    }
}
Run Code Online (Sandbox Code Playgroud)


Seb*_*jas 18

现在(至少形成ASP.NET MVC 5),您可以使用UrlAttribute,其中包括服务器和客户端验证:

[Url]
public string WebSiteUrl { get; set; }
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您希望使用MVC DataAnnotations验证url字符串,则可以通过帖子的标题编写自定义验证器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Phil Haack有一个超越这个的好教程,还包括通过jQuery添加代码以在客户端进行验证:http: //haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx


小智 5

使用URL属性怎么样,比如:

public class ProveedorMetadata
{
    [Url()]
    [Display(Name = "Web Site")]
    public string SitioWeb { get; set; }
}
Run Code Online (Sandbox Code Playgroud)