Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - mvc4 url validation

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...