mvc4 url validation

左心房为你撑大大i 提交于 2019-12-18 13:59:12

问题


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 follows

[Required(ErrorMessage = "Required Field")]
[Url(ErrorMessage="Please enter a valid url")]
[DisplayName("Website")]
public string web { get; set; }

in the view, I have this

@Html.EditorFor(model => model.web, new { AutoCompleteType = "Disabled", autocomplete = "off" })

now the problem lies in how the input text for this field is validated in the client side. the field must have the protocol prefix at all times, otherwise it becomes invalid.

what is the best way I can fix this issue?

Many Thanks


回答1:


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




回答2:


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")]


来源:https://stackoverflow.com/questions/15249105/mvc4-url-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!