JS form表单数据校验及失效情况下的解决方案


如下图,当执行提交操作之前,我们需要对序号,要求完成时间,责任人,措施内容四项进行非空,字符长度及输入内容的类型进行校验.

直接贴样式代码

class="wrapper animated fadeInRight"> <form id="form" class="form-horizontal m">
class="form-group">
class="col-sm-8"> "longEventId" col="LongEventId" type="hidden" class="form-control" /> "stepNo" name="stepNoName" col="StepNo" type="number" class="form-control" />
class="form-group">
class="col-sm-8"> "finishTime" name="finishTime" col="FinishTime" type="text" class="time-input form-control" autocomplete="off" placeholder="要求完成时间" />
class="form-group"> @*"personLiableId" col="PersonLiableId" type="text" class="form-control" />*@ @await Html.PartialAsync("/Areas/SystemManage/Shared/SystemUserIdSelect.cshtml", new ViewDataDictionary(this.ViewData) { { "Content", "8" }, { "IsMultiple", "false" } }) "userId" name="userIdName" col="PersonLiableId" type="hidden" class="form-control" />
class="form-group">
class="col-sm-8">
class="form-group">
class="col-sm-8">
class="form-group">
class="col-sm-8">
"stepPic" class="img-box">
form>

下面为文本输入检测代码

先看下当点击提交的时候的效果图:

 当我们点击提交时,序号,要求完成时间,措施内容都提示是必填字段.

因此当提交时,这个表单验证是不会通过的,也就不会执行ajax请求调用提交方法.

if ($('#form').validate().form()) {
            var postData = $('#form').getWebControls({Id: id });
            postData.StepPic = $("#stepPic").imageUpload("getImageUrl");
            ys.ajax({
                url: '@Url.Content("~/LongEventManage/LongMeasuresManage/SaveFormJson")',
                type: 'post',
                data: postData,
                success: function (obj) {
                    if (obj.Tag == 1) {
                        ys.msgSuccess(obj.Message);
                        parent.searchGrid();
                        parent.layer.close(index);
                    }else {
                        ys.msgError(obj.Message);
                      }
                    }
                });
            }
        }

咱们接着往下实验,如果此时我们输入了措施内容,但是字符大于规定的300长度时,

stepContentName: {required: true, maxlength: 300 }

关于rules的key,其实指向的中的name,之前我选择的是id,但是却没有生效,必须指向他的name名称.

 细心的小伙伴,有没有发现,我的完成时间,为什么没有用name,而是还用的id名称?

stepNoName" col="StepNo" type="number" class="form-control" />
finishTimeName" col="FinishTime" type="text" class="time-input form-control" autocomplete="off" placeholder="要求完成时间" />
 $('#form').validate({
        rules: {
            stepNoName: {required: true},
            finishTime: {required: true},
            userId:{required: true},
            stepContentName: {required: true, maxlength: 300  }
            }
        });
    });

因为上面的