asp.net mvc dataannotation验证url

时间:2022-02-18 16:38:52

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

有人能告诉我如何验证http://www.abc.com这样的url吗

8 个解决方案

#1


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:

如果您希望使用MVC dataannotation来验证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;
    }
}

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

Phil Haack有一个很好的教程,它超越了这一点,还包括通过jQuery在客户端验证代码:http://haacked.com/archive/2009/11/19/aspnetmvc2-定制valides.aspx。

#2


36  

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

让系统。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 ));
    }
}

#3


11  

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

如果您正在使用MVC3 RTM,您可以使用[URL]验证属性。

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

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

#4


8  

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

现在(至少形成ASP。您可以使用UrlAttribute,包括服务器和客户端验证:

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

#5


0  

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

使用正则表达式数据注释,并使用如下的regex:

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 ?因此,如果可选,可以将正则表达式改为:

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

#6


0  

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

我使用这个正则表达式来表示我站点上的内部或外部url。

((?:https?\:\/\/|\/.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)

#7


0  

Here is proper validation attribute code used in prod system:

以下是prod系统中使用的正确验证属性代码:

[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;
    }
}

#8


0  

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

Uri。IsWellFormedUriString检查URL格式是否正确,不需要转义。

/// <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);
    }
}

#1


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:

如果您希望使用MVC dataannotation来验证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;
    }
}

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

Phil Haack有一个很好的教程,它超越了这一点,还包括通过jQuery在客户端验证代码:http://haacked.com/archive/2009/11/19/aspnetmvc2-定制valides.aspx。

#2


36  

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

让系统。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 ));
    }
}

#3


11  

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

如果您正在使用MVC3 RTM,您可以使用[URL]验证属性。

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

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

#4


8  

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

现在(至少形成ASP。您可以使用UrlAttribute,包括服务器和客户端验证:

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

#5


0  

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

使用正则表达式数据注释,并使用如下的regex:

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 ?因此,如果可选,可以将正则表达式改为:

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

#6


0  

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

我使用这个正则表达式来表示我站点上的内部或外部url。

((?:https?\:\/\/|\/.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)

#7


0  

Here is proper validation attribute code used in prod system:

以下是prod系统中使用的正确验证属性代码:

[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;
    }
}

#8


0  

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

Uri。IsWellFormedUriString检查URL格式是否正确,不需要转义。

/// <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);
    }
}