jQuery使用Ajax请求进行规则验证

时间:2018-10-09 05:48:44

标签: jquery ajax validationrules

这个问题已经问了,但是没用。

我想使用jQuery对显示Zone Name Already Exist...!消息进行Ajax规则验证。我尝试了submitHandler,但没有用。

这是我的代码

$(document).ready(function() {
$('#submitBtn').click(function() {
    $("#zoneForm").validate({
        rules: {
            'zoneName': {
                minlength: 4,
                maxlength: 15
            }
        },
        validClass: "success",
        highlight: function(element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        success: function(element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        },
        submitHandler: function(e) {
            var zoneVal = $('#zoneName').val();
            console.log(zoneVal);
            e.preventDefault();
            if (zoneVal) {
                $.ajax({
                    url: '<?php echo base_url();?>zone/zoneCheck',
                    type: "POST",
                    dataType: "json",
                    data: {
                        zoneName: zoneVal
                    },
                    success: function(data) {
                        console.log(data);
                        alert(data);
                        if (data == 1) {
                            alert('Zone Name Already Exist.');
                        } else if (data == 0) {
                            $("#zoneForm").submit();
                        }
                    }
                });
            }
        },
    });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src=""></script>
<form id="zoneForm" name="zoneForm" method="POST" action="<?php echo site_url('zone/editzone');?>">
	<label>Zone Name <span class="required-label">*</span></label>
  <input type="text" class="form-control zoneEditName" id="zoneEditName" name="zoneName" placeholder="Enter Zone Name" required />
  <input class="btn btn-success zoneSubmit" type="submit" id="submitBtn" name="submit" value="Submit" >
</form>

1 个答案:

答案 0 :(得分:0)

在jquery中使用远程功能可能会帮助您检查isExists

请参见以下示例

$( "#myform" ).validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $( "#username" ).val();
          }
        }
      }
    }
  }
});

或者您可以参考https://jqueryvalidation.org/remote-method/