jquery - Html.BeginForm 使用 onSubmit 进行验证

标签 jquery .net asp.net-mvc

我正在尝试提交我的表单,但是我添加了一些有效的 jquery 进行验证:

    $(function validateForm() {
    $("#newMonoReading").on('focusout', function () {
        var str = "";

        var initialMonoReading = $('#InitialMonoReading').val();
        var newMonoReading = $('#newMonoReading').val()
        if (~~newMonoReading < ~~initialMonoReading) {
            $('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
            $('#MonoErrorMessage').show();
            return false;


        } else {
            $('#MonoErrorMessage').hide();

        }
    });
});

但是问题出在提交按钮上

  <input type="submit" value="Submit" class="btn btn-primary">

如果出现错误,提交按钮仍然有效,我需要它不显示错误消息,然后发送,但我尝试使用表单的 onsubmit 但它不起作用,即使值较小,它仍然会提交显示错误消息。

这是 html.BeginForm。我认为错误可能就在这里。我不太确定。

         <div class="modal-body">
        @using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm()" }))
        {

任何想法

最佳答案

这是正确的摘要吗?

On submit you want to validate your form with your jQuery function. If validation is passed then you want the submit to be continued, otherwise you want the submit to be canceled.

如果我的总结不正确,请进一步澄清您的问题。

如果我总结准确的话,你可以将你的 jQuery 函数更改为:

$(function validateForm(event) {
  event = event || window.event || event.srcElement;
  var initialMonoReading = $('#InitialMonoReading').val();
  var newMonoReading = $('#newMonoReading').val()
  if (~~newMonoReading < ~~initialMonoReading) {
    $('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
    $('#MonoErrorMessage').show();
    event.preventDefault();
  }
  else {
    $('#MonoErrorMessage').hide();
  }
});

在创建标记时,使用以下行:

@using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))

关于jquery - Html.BeginForm 使用 onSubmit 进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26970867/

相关文章:

c# - 将 Razor 代码放入 JavaScript var 中

.net - 在 IIS 中使用 IP 地址绑定(bind)子应用程序

javascript - 通过 javascript 访问转发器中的 asp 元素

c# - 如何通过 SignalR 将遥测数据推送到客户端?

javascript - IE designMode 显示显示 :none Divs

c# - .NET 与单声道 : different results for conversion from 2^32 as double to int

c# - 无法在 C# 中将 BsonArray 转换为 BsonDocument

asp.net-mvc - Kendo Grid MVC 结合了 ajax 绑定(bind)和服务器编辑

jQuery 添加变量

javascript - 来自返回 JSON 的 KendoUI 网格页脚附加内容