asp.net mvc dataannotation validating url

后端 未结 9 709
离开以前
离开以前 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: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 ));
        }
    }
    

提交回复
热议问题