2017-04-21 69 views
2

我在ASP.Net中有一個視圖。我在視圖中添加了一些控件。我正在嘗試在將數據發送到服務器之前進行客戶端驗證。如果一切正常,我想將它發送到服務器。
我的代碼是在這裏:發送數據到服務器之前的客戶端驗證ASP.Net MVC

 @using (Html.BeginForm("Index", "staff", FormMethod.Post)) 
      { 
      @Html.AntiForgeryToken() 
      @Html.ValidationSummary(true) 

      <div class="form-group has-feedback"> 
       <div> @Html.LabelFor(a => a.staff_name, "Staff Name")</div> 
       @Html.TextBoxFor(a => a.staff_name, new { @class = "form-control", placeholder = "", required = "required", autofocus = "autofocus"}) 
      </div> 
        <div class="form-group has-feedback"> 
         <div> @Html.LabelFor(a => a.user_name, "Username")</div> 
         @Html.TextBoxFor(a => a.user_name, new { @class = "form-control", placeholder = "", required = "required" }) 

        </div> 
        <div class="form-group has-feedback"> 
         <div> @Html.LabelFor(a => a.password, "Password")</div> 
         @Html.PasswordFor(a => a.password, new { @class = "form-control", placeholder = "", required = "required",id="password" }) 

        </div> 
        <div class="form-group has-feedback"> 
         <div> @Html.LabelFor(a => a.confirm_password, "Confirm Password")</div> 
         @Html.PasswordFor(a => a.confirm_password, new { @class = "form-control", placeholder = "", required = "required", id = "c_password" }) 

        </div> 

        <div class="row"> 
         <div class="col-xs-3 "> 
          <button type="submit" class="btn btn-primary btn-md pull-right" onsubmit="validateForm()">Submit</button> 
         </div><!-- /.col --> 
        </div> 
     } 
    </div> 
</section> 
<script type="text/javascript"> 
    function validateForm() 
    { 
     var pass = document.getElementById("password").value; 
     var c_pass = document.getElementById("c_password").value; 

     if(pass==c_pass) 
     { 
      //submit 
     } 

    } 

</script> 

我要檢查,如果「密碼」和「確認密碼」相匹配或not.If肯定的,那麼只發布在服務器中。

+0

您可以使用此https://stackoverflow.com/a/44473848/3089009 – hasan

+0

我的答案是否奏效? – hasan

回答

0

您應該啓用與@{ Html.EnableClientValidation(true); }客戶端驗證@Html.BeginForm之前和使用jquery validate()

使用這種激活客戶端驗證。

<script type="text/javascript"> 
     $(document).ready(function() { 
      $("#yourFormId").validate({ 
       rules: { 
        ConfirmPassword: { 
         equalTo: "#Password" 
        }, 
       }, 
       messages: { 
        confirm_password: { 
         equalTo: "Please enter the same password as above" 
        }, 
       } 
      }); 
     }); 
</script> 
0

嘿,你只需要在你的web.config文件中啓用客戶端驗證,不需要編寫任何外部代碼。 您可以添加下面的一行代碼在你的web.config文件

希望工程爲您服務!

+0

我在web.config文件中已經有了這些代碼。我想要的是讓Javascript驗證輸入。僅在驗證後,將數據提交給服務器。 –

相關問題