如何实现MVC3模型URL验证?

时间:2012-05-15 18:02:55

标签: asp.net-mvc-3 validation

我已经成功实现了客户端验证,要求在我的文本框中输入。但是,我想评估文本框的内容,看它是否是格式良好的URL。这是我到目前为止所拥有的: Index.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" />

ValidationModel:

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

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

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

非常感谢:)

2 个答案:

答案 0 :(得分:6)

您可以使用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操作方法中,您可以调用ModelState.IsValid属性,该属性将为您检查验证。

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

}

答案 1 :(得分:5)

好方法是在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; }