使用jquery验证插件在发送回调函数中不会触发表单验证

时间:2015-04-16 07:48:50

标签: javascript jquery forms validation

我是jQuery的新手。我做了一个简单的任务,使用jQuery验证插件验证表单数据。

我创建了一个简单的表单

<html>
<head>
	<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
	<script src="js/jquery.validate.js"></script>
	<script src="js/form-validate.js"></script>
</head>
<body>
	<form class="cmxform" id="commentForm" method="get" action="">
	  <fieldset>
	    <legend>Please provide your name, email address (won't be published) and a comment</legend>
	    <p>
	      <label for="cname">Name (required, at least 2 characters)</label>
	      <input id="cname" name="name" minlength="2" type="text" class =" requiredFieldCheck ">
	    </p>
	    <p>
	      <label for="cemail">E-Mail (required)</label>
	      <input id="cemail" type="email" name="email" required>
	    </p>
	    <p>
	      <label for="curl">URL (optional)</label>
	      <input id="curl" type="url" name="url">
	    </p>
	    <p>
	      <label for="ccomment">Your comment (required)</label>
	      <textarea id="ccomment" name="comment" required></textarea>
	    </p>
	    <p>
	      <input class="submit" type="submit" value="Submit">
	    </p>
	  </fieldset>
	</form>
<script>
//$("#commentForm").validate();
$(function(){

        $('#commentForm').ajaxForm({
        beforeSend:function(){
            alert('before send');
            $('#commentForm').validate();
        },
        success:function(){
            
            alert("when success");
            
        },
        error:function(){
            alert('when unsuccess');
        }
    });

    $('#commentForm').ajaxSubmit();

    // return false to prevent normal browser submit and page navigation 
    return false;
});
</script>
</body>
</html>

$.validator.addMethod("requiredFieldCheck", function (value, element) {
    alert("working method requiredFieldCheck "+value);
    var result;
    	if(value.length > 3){
		result = true ;
	}
	else{
		result = false ;
	}
	return result;
}, '****This content must be greater than 3 characters****');
并且在浏览器控制台中它被错误捕获Uncaught TypeError:undefined不是函数 任何人都可以给我一些建议,在发送数据和使用jquery验证插件之前进行表单验证吗? 在此先感谢

1 个答案:

答案 0 :(得分:0)

您需要注册适配器,例如:

jQuery.validator.unobtrusive.adapters.addSingleVal("requiredFieldCheck", "other");