2017-05-10 27 views
0

我試圖讓字段在選項卡上驗證而不是提交。有什麼方法可以使這項工作?我認爲這將是一個改變事件的JQuery腳本,但我不知道將使用什麼方法。使用ASP.NET實體框架驗證Tab Out上的字段

這是我目前正在修改的腳本,它只是運行一個名爲GetUserDetails的方法,它與此問題無關並自動填充我的字段。我也需要它來運行或觸發驗證。它需要知道用戶名是否存在,但在我嘗試使用alert方法時,在這種情況下似乎不起作用。

<script> 
    $('#username').on("change", function (event) { 
     var userName = $('#username').val(); 
     //make an ajax request 
     var model = JSON.parse('{"userId":"' + userName + '"}'); 

     //precess the retrieved json 

     //place json fields on the input boxes in html 

     $.ajax({ 
      type:"POST", 
      url: "/Employees/GetUserDetails/", 
      data: model, 
     }).done(function (data) { 
      if (data.FullName == null || data.FullName == "") { 
       $('#username').alert("Username does not exist."); 
      } 
      $('#fullname').val(data.FullName); 
      $('#email').val(data.email); 
      $('#phone').val(data.phone); 
     }); 
    }); 
</script> 

我要它做什麼,如果我打提交相反,對於給定的領域它會怎麼做。我的模型有驗證的註釋。

+0

標籤拖出意味着什麼? –

+0

從字段中跳出觸發更改事件是。 –

回答

0

更新: 在您提交表單之前,您無法驗證它。 https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs

但我們可以做的是在客戶端進行自定義驗證。

===========================

你可以使用.blur()檢測丟失的焦點。

模糊事件失去焦點時發送給元素。如果你離開元素的事件 https://api.jquery.com/blur/

$(function(){ 
 
    $('#txt').on("blur", function (event) { 
 
    if ($(this).val() == ""){ 
 
     alert("please input value"); 
 
    } 
 
    else{ 
 
    var userName = $('#username').val(); 
 
     //make an ajax request 
 
     var model = JSON.parse('{"userId":"' + userName + '"}'); 
 

 
     //precess the retrieved json 
 

 
     //place json fields on the input boxes in html 
 

 
     $.ajax({ 
 
      type:"POST", 
 
      url: "/Employees/GetUserDetails/", 
 
      data: model, 
 
     }).done(function (data) { 
 
      $('#fullname').val(data.FullName); 
 
      $('#email').val(data.email); 
 
      $('#phone').val(data.phone); 
 
     }); 
 
    } 
 
    }) 
 

 
    
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" name="sample" id="txt"/> 
 
    <input type="text" name="sample2" id="txt1"/>

+0

不,在改變時,我想要做的是觸發內置的模型驗證模式。如果我點擊提交,那麼我想讓它做它會做的事。我的模型有驗證的註釋。也許我應該將這些添加到問題中。 –

+0

如果沒有提交表單 –

+0

,你不能擁有該網頁https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-註解驗證-CS –