asp.net mvc dataannotation validating url

后端 未结 9 707
离开以前
离开以前 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.

    /// 
    /// Ensures the property is a valid URL.
    /// 
    [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);
        }
    }
    

提交回复
热议问题