mvc4 url validation

前端 未结 2 1306
滥情空心
滥情空心 2020-12-15 17:01

I\'m writing this question here after trying to find an answer for two days.

basically here\'s what\'s going on.

I have a property in the viewmodel as follow

相关标签:
2条回答
  • 2020-12-15 17:25

    You can do this using the DataAnnotationsExtensions library. They have an UrlAttribute that you can configure to only validate when a protocol is specified. This attribute also supplies client-side validation. You can see an example of this behavior here: http://dataannotationsextensions.org/Url/Create

    You can use this attribute as follows:

    using System.ComponentModel.DataAnnotations;
    
    namespace DataAnnotationsExtensions.Core
    {
        public class UrlEntity
        {
            [Url]
            [Required]
            public string Url { get; set; }
    
            [Url(UrlOptions.OptionalProtocol)]
            [Required]
            public string UrlWithoutProtocolRequired { get; set; }
    
            [Url(UrlOptions.DisallowProtocol)]
            [Required]
            public string UrlDisallowProtocol { get; set; }
        }
    }
    

    For your purposes, the first option suffices.

    The package of this library (with ASP.NET MVC support included) can be found on NuGet: Install-Package DataAnnotationsExtensions.MVC3

    Note: this also works fine with ASP.NET MVC 4

    0 讨论(0)
  • 2020-12-15 17:28

    Not sure if I fully understand the question. Are you trying to validate for correctly formed URLs? If so you could implement a RegularExpression DataAnnotation as follows:

    [RegularExpression(@"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", ErrorMessage = "My Error Message")]
    
    0 讨论(0)
提交回复
热议问题