asp.net mvc dataannotation validating url

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

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

9条回答
  •  萌比男神i
    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;
        }
    }
    

提交回复
热议问题