2

Html 5 url 验证默认需要http://https://。我尝试使用自定义正则表达式添加模式属性,但与 type="url" 一起,但未能这样做。

是否有任何选项可以覆盖正则表达式以使 http://https://可选?

4

2 回答 2

2

请尝试使用此正则表达式来验证不带“http://”、“https://”或“www”的 url :

//Validates url without "http://", "https://" or "www"
[RegularExpression(@"((www\.|(http|https|ftp|news|file|)+\:\/\/)?[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])", ErrorMessage = "Please check the url")]

希望这可以帮助...

于 2015-03-25T15:06:01.527 回答
0
  1. 您可以使用“DataAnnotationsExtensions”库(mvc4 url​​ 验证)。

但它太旧了,我不知道它如何与最新的 MVC 版本一起使用。

  1. 我的解决方案。不在模型中验证,将 URL 显示为超链接:

模型:

public class MyClass
    {
        public int Id { get; set; }
        public string WebSite { get; set; }
    }

看法:

@foreach (var item in Model) {
    <tr>
        <td>
            <a target="_blank" href="http://@Html.DisplayFor(modelItem => item.WebSite)">@Html.DisplayFor(modelItem => item.WebSite)</a>
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr> }
于 2015-10-14T03:58:56.737 回答