mvc4 URL验证 [英] mvc4 url validation

查看:232
本文介绍了mvc4 URL验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到答案两天后,在这里写这个问题。

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

现在的问题在于如何为这一领域的输入文本在客户端进行验证。现场必须在任何时候都协议preFIX,否则无效。

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?

非常感谢

推荐答案

您可以使用 DataAnnotationsExtensions库做到这一点。他们有一个 UrlAttribute ,您可以配置为仅指定了协议时验证。此属性还提供客户端验证。你可以看到这里的此行为的示例:<一href=\"http://dataannotationsextensions.org/Url/Create\">http://dataannotationsextensions.org/Url/Create

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.

这个库的包(在ASP.NET MVC支持包括)可的NuGet中找到:
    安装封装DataAnnotationsExtensions.MVC3

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

请注意:这也正常工作与ASP.NET MVC 4

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

这篇关于mvc4 URL验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆