asp.net mvc dataannotation validating url

后端 未结 9 708
离开以前
离开以前 2021-02-04 05:23

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

相关标签:
9条回答
  • 2021-02-04 05:41

    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; }
    
    0 讨论(0)
  • 2021-02-04 05:43

    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

    0 讨论(0)
  • 2021-02-04 05:46

    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

    0 讨论(0)
  • 2021-02-04 05:59

    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;
        }
    }
    
    0 讨论(0)
  • 2021-02-04 05:59

    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)
    
    0 讨论(0)
  • 2021-02-04 06:03

    What about using URL attribute, like:

    public class ProveedorMetadata
    {
        [Url()]
        [Display(Name = "Web Site")]
        public string SitioWeb { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题