如何实现MVC3模型URL验证?

Sid*_*idC 4 validation asp.net-mvc-3

我已经成功实现了客户端验证,以便在我的文本框中输入.但是,我想评估文本框的内容,看它是否是格式良好的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" />
Run Code Online (Sandbox Code Playgroud)

ValidationModel:

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

public class ValidationModel
{
    [Required]
    public string URL {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

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

非常感谢:)

Shy*_*yju 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;}
}
Run Code Online (Sandbox Code Playgroud)

在您的HTTPPostAction方法中,您可以调用ModelState.IsValid将为您检查Validations 的属性.

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

}
Run Code Online (Sandbox Code Playgroud)


Sal*_*nAA 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;%\$#_]*)?$")
    {}
}
Run Code Online (Sandbox Code Playgroud)

所以在模型上:

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