0
votes

I have a model that validates that a field is for a URL.

    /// <summary>
    /// Gets or sets the url of the event.
    /// </summary>
    [DisplayName("Event URL")]
    [Url(ErrorMessage = "URL must be a valid URL.")]
    public string EventURL { get; set; }

In addition, I have some custom validation in my model. I validate the model by checking the ModelState.IsValid property and also with:

            var validationResults = new List<ValidationResult>();

            bool isValid = Validator.TryValidateObject(
                model,
                new ValidationContext(model, null, null),
                validationResults,
                false);

I return the view with the model updated and a property SubmissionErrors with the validation results from validating the model. I then return View(model);

In my view I have a validation box that displays when an error occurs. It should display all the validation results and any other errors. I've thrown in @Html.ValidationMessageFor(m => m.EventURL) and @Html.ValidationSummary() with both of them not displaying the error to the user when they submit an invalid URL. I'm not sure what I am doing wrong and I can't seem to locate any reason why this would be occur. Am I utilizing the URL tag incorrectly, or the validation message incorrectly? Any help would be appreciated.

1

1 Answers

0
votes

TryValidateObject validateAllProperties set be true.

if validateAllProperties parameter is true validate all properties if not check be only required properties

  bool isValid = Validator.TryValidateObject(
                        model,
                        new ValidationContext(model, null, null),
                        validationResults,
                        true);

Imported Note : If model property is not required, null values are not validated.

Your model property is not required. Add property Required then will be validate

        [DisplayName("Event URL")]
        [Url(ErrorMessage = "URL must be a valid URL.")]
        [Required(ErrorMessage = "Field Must be Required")]
        public string EventURL { get; set; }

Another way

If Model property must be required

  public ActionResult About(Aboute model)
            {
                var validationResults = new List<ValidationResult>();
                // Clear ModelState check after validate
                ModelState.Clear();
                // Get validate ErrorMessage and status if you need.
                // This code not set modelState
                bool isValid = Validator.TryValidateObject(
                    model,
                    new ValidationContext(model, null, null),
                    validationResults,
                    true);
              // Check View Model validation and set modelState    
              TryValidateModel(model);

               return View(model)
            }

Or Will be use CutomValidation

   public class CustomUrlAttribute : ValidationAttribute
    {
        public CustomUrlAttribute()
        {

        }

        private bool IsUrlValid(string url)
        {
            string pattern =
                @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
            Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return reg.IsMatch(url);
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                ErrorMessage = "Field Must be required";
                return false;
            }
            string strValue = value as string;

            if (!IsUrlValid(strValue))
            {
                ErrorMessage = "Invalid URL";
                return false;
            }

            return true;
        }
    }



 public class ContactModel
    {
        [DisplayName("Event URL")]
        [CustomUrlAttribute()]           
        public string EventURL { get; set; }    
    }

You can look at here dataAnnotations model validation for an example bilisim.io Custom validation and Model Validation articles