【问题标题】:How to Implement MVC3 Model URL Validation?如何实现 MVC3 模型 URL 验证?
【发布时间】:2012-05-15 18:02:55
【问题描述】:

我已成功实施客户端验证,要求在我的文本框中输入。但是,我想评估文本框的内容以查看它是否是格式正确的 URL。到目前为止,这是我所拥有的: 索引.cshtml:

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>
@model Ticket911.Models.ValidationModel                          
@{
ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
@using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainer" , OnSuccess = "$.validator.unobtrusive.parse('form');" }))

{
<p>
    Error Message: @Html.ValidationMessageFor(m => m.URL)
</p>
<p>
@Html.LabelFor(m =>m.URL):
@Html.EditorFor(m => m.URL)
</p>
<input type="submit" value="Submit" />

验证模型:

 public class ValidURLAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return (value != null);
    }
}

public class ValidationModel
{
    [Required]
    public string URL {get; set;}
}

如何确保模型 URL 验证发生?单击提交按钮时,必须执行什么操作才能导航到输入到文本框中的 URL?

非常感谢:)

【问题讨论】:

    标签: asp.net-mvc-3 validation


    【解决方案1】:

    您可以通过DataAnnotations 完成此操作

    public class ValidationModel
    {
      [Required]
      [RegularExpression(@"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$", ErrorMessage = "URL format is wrong")]
      public string URL {get; set;}
    }
    

    在您的HTTPPost Action 方法中,您可以调用ModelState.IsValid 属性,该属性将为您检查验证。

    [HttpPost]
    public ActionResult Save(ValidationModel model)
    {
      if(ModelState.IsValid)
      {
       //Save or whatever
      }
      return View(model);
    
    }
    

    【讨论】:

    • 太棒了:) 然后如何在新页面上显示在 HttpPost 中传递的 URL 中包含的超链接列表?
    • @SidC:URL 中的超链接是什么意思?网址中有哪些超链接?
    【解决方案2】:

    好方法是实现您的属性以供下次在 mvc 项目中使用。像这样:

    public class UrlAttribute : RegularExpressionAttribute
    {
        public UrlAttribute() : base(@"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$")
        {}
    }
    

    以此类推:

    [Url(ErrorMessage = "URL format is wrong!")]
    public string BlogAddress { get; set; }
    

    【讨论】:

      猜你喜欢
      • 2012-01-05
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 2016-04-06
      • 2021-08-05
      相关资源
      最近更新 更多