2013-07-04 91 views
1

任何人都可以幫助發現我的代碼出錯的地方,即使表單字段無效,我也無法阻止表單提交,我一直在這一整天,並嘗試了很多方法,但沒有運氣。如果驗證失敗,防止表單提交

[Display(Name = "Amount to convert")] 
    [Required(ErrorMessage = " is required")] 
    [RegularExpression("^[0-9]+$", ErrorMessage = " requires numbers only")] 
    [Range(1, int.MaxValue, ErrorMessage = " must be more than 1")] 





$(function() { 
     // $("#frmWeightsMeasures").validate(); 
     $("#frmWeightsMeasures").submit(function(event) { 
      // var isvalidate = $("#frmWeightsMeasures").valid(); 
      // if (isvalidate) { 
       event.preventDefault(); 
      // } 
      $.ajax({ 
       type: "POST", 
       cache: true, 
       url: form.attr("action"), 
       data: form.serialize(), 
       dataType: "json", 
       error: searchFailed, 
       success: function(weightsData) { 
        $("#DisplayConversion").html(weightsData.DisplayConversion); 
       } 
      }); 
     }); 
    }); 

    function searchFailed(xhr, errorType, exception) { 
     var errorMessage = exception || xhr.statusText; 
     $("#DisplayConversion").html("Sorry, there was a problem with the search."); 
    } 

我已經添加下面的工作代碼,希望這將幫助別人的未來,故事的摩托車,當修改您的代碼,看你刪除的內容。

$(function() { 
      $("#frmWeightsMeasures").validate(); 
      $("#frmWeightsMeasures").submit(function(event) { 
       var isvalidate = $("#frmWeightsMeasures").valid(); 
       if (isvalidate) { 
        event.preventDefault(); 
        var form = $(this); 
        $.ajax({ 
         type: "POST", 
         cache: true, 
         url: form.attr("action"), 
         data: form.serialize(), 
         dataType: "json", 
         error: searchFailed, 
         success: function(weightsData) { 
          $("#DisplayConversion").html(weightsData.DisplayConversion); 
         } 
        }); 
       } 
      }); 
     }); 

     function searchFailed(xhr, errorType, exception) { 
      var errorMessage = exception || xhr.statusText; 
      $("#DisplayConversion").html("Sorry, there was a problem with the search."); 
     } 
+0

提交如果刪除'[必填]',不它返回正確的錯誤? – andreister

+0

嗨andreister,沒有我然後得到默認mvc錯誤金額轉換是必需的,而不是隻是'是必需的' – CareerChange

回答

2

你實際上並沒有引用表單,這就是爲什麼它沒有定義。你需要你的Ajax調用之前將以下:

var form = $(this);

此外,對於驗證:

return $(form).valid()將防止形式,如果無效

+1

我已經花了長期試圖解決這個問題,並嘗試了不同的方式,直到大約2分鐘前,我才意識到我刪除了這一行代碼:var form = $(this);加回來,現在工作正常。對不起,花了很長時間看電腦 – CareerChange

1

你可能想嘗試event.preventdefault()和event.stopPropagation()

單獨的preventDefault仍允許誤差泡了,你想要什麼這可能不是。

+0

嗨EJ Brennan,仍然得到相同的錯誤,0x800a1391 - JavaScript運行時錯誤:'form'是undefined – CareerChange

0

我認爲最好的是在錯誤的情況下返回false,而不是.preventDefault();

相關問題