2016-07-14 57 views
1

我將客戶端驗證應用於我的表單中的字段,以便它們不保留爲空。但是,該消息顯示在輸入字段的下面。我怎樣才能讓它們出現在場地旁邊?爲mvc表單字段定位驗證消息

表單字段:

@using (Html.BeginForm("SaveAccount", "RxCard", FormMethod.Post, new { id = "save", enctype = "multipart/form-data" })) 
{    
    <label id="lblAccountName">Account Name</label> 
    @Html.TextBoxFor(model => model.Pharmacy.AccountName, new { @id = "txtAccountName", @Name = "txtAccountName", required = "required" }) 
    ... 
} 

的Jquery:

$(document).ready(function() { 

    $('#save').validate({ 
     onchange: function (element) { 
      this.element(element); 
      console.log('onchange fired'); 
     }, 
     onfocusout: function (element) { 
      this.element(element); 
      console.log('onfocusout fired'); 
     } 
    }); 

}); 

結果:

enter image description here

+0

您使用HTML-5的驗證是由您的瀏覽器控制器。使用MVC的內置驗證功能(使用驗證屬性和@ Html.ValidationMessageFor())來獲得客戶端和服務器端驗證,並允許您定位/設置消息的樣式。注意:不要試圖用'@Name =「txtAccountName」'覆蓋'name'屬性 - 它保證模型綁定將失敗 –

+0

您正在使用哪種css進行設計? –

+0

@StephenMuecke的事情是,我需要驗證發生onchange事件。這就是爲什麼我沒有在我的模型中使用驗證屬性。有沒有一種方法來調整驗證信息,以便在onchange上發生? – thatdude

回答

1

使用MVC的內置的ModelState驗證的這個樣子。

[HttpPost] 
public ActionResult SaveAccount(Account account) 
{ 
    // It's return true when AccountName have some value, return false if it's NULL 
    if (!ModelState.IsValid) 
    { 
     // Return to the page with the Validation errorsMessages. 
     return View(); 
    } 
    return RedirectToAction("YOUR VIEW NAME"); 
} 

你的類

public Class Account 
{ 
    [Required(ErrorMessage = "AccountName is required")] 
    public string AccountName { get; set; } 
} 

的cHTML頁

// I am using bootstrap for Showing your error Next to the Textbox 
@using (Html.BeginForm("SaveAccount", "RxCard", FormMethod.Post, new { id = "save", enctype = "multipart/form-data" })) 
{ 
<div class="row-fluid"> 
    <div class="span3"> 
     <label id="lblAccountName">Account Name</label> 
    </div> 
    <div class="span6"> 
     @Html.TextBoxFor(model => model.AccountName, new { @id = "txtAccountName", @Name = "txtAccountName", required = "required" }) 
     @Html.ValidationMessageFor(model => model.AccountName, "", new { @id = "accountID", @class = "text-danger", style = "color:red;" }) 
    </div> 
</div> 
} 

UPDATE

您可以在文本框,以驗證在client side.添加一個簡單onChangeblur事件,只是分配一個IDValidationMessageFor正如我上面添加。

$("#AccountName").change(function() 
{ 
    // change this with your own condition.. 
    if ($("#AccountName").val() != 0) 
    { 
     $("#accountID").text("This field is not correct"); 
     $("#accountID").attr('class', 'field-validation-error'); 
    } 
}); 

您也可以使用您的服務器端驗證與此JQuery event

瞭解更多關於Using Data Annotations for Model Validation

+0

我肯定會採取這種方法,但我可以修改驗證,以便它發生onchange事件?我需要在用戶退出該字段後進行驗證。 – thatdude

+0

是的,請參閱最新的答案。 –

+0

太棒了!這是我需要的。謝謝你,先生。 – thatdude