asp.net mvc dataannotation validating url

后端 未结 9 710
离开以前
离开以前 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 06:04

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

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

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

    ((?:https?\:\/\/|\/.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)
    
    0 讨论(0)
提交回复
热议问题