2012-05-15 74 views
4

我已經成功實現了客戶端驗證,要求在我的文本框中輸入。但是,我想評估文本框的內容以查看它是否是格式正確的URL。下面是我迄今: Index.cshtml:如何實現MVC3模型URL驗證?

<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?

感謝很多:)

回答

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; } 
6

你可以做到這一點wtih 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); 

} 
+0

太棒了:)我怎麼然後顯示包含在在HttpPost通過了新的頁面上的URL超鏈接的列表? – SidC

+1

創建一個新問題。 –

+0

@SidC:你的意思是URL中的超鏈接?什麼超鏈接你會在網址? – Shyju