【问题标题】:Adding in jQuery validate添加 jQuery 验证
【发布时间】:2016-01-24 02:31:21
【问题描述】:

我正在观看有关将 jQuery 验证添加到联系表单的视频教程,但没有一个有效。他们从来没有真正讨论过如何将验证插件添加到页面,所以我想这可能是我出错的地方。

他在页面顶部的 jQuery 调用是这样的:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

再一次,他只是去谷歌 jQuery validate 并且它会出现,所以我认为它是这样的:

http://jqueryvalidation.org/

有没有人认为我所做的事情有什么问题?我得到了实际的表单,而不是 jQuery 验证。

jQuery(document).ready(function($){
		$("#contactform").validate({
			rules: {
				name: {
					required: true;
					minlength: 2
				},
				email: {
					required: true;
					email: true;
				},
				message: {
					required: true;
					minlength: 5
				}
			},
			messages: {
				name: {
					required: "Please enter your name",
					minlength: "Your name seems a bit short, doesn't it?"
				},
				email: {
					required: "Please enter your email address",
					email: "Please enter a valid email address"
				},
				message: {
					required: "Please enter your message",
					minlength: "Your message seems a bit short. Please enter at least 5 characters"
				}
			}
		});
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form id="contactform" method="post" action="" novalidate>

			<input type="text" name="name" placeholder="Name">
			<input type="email" name="email" placeholder="Email">
			<textarea name="message" placeholder="Message"></textarea>
			<input type="submit" name="submitform" value="Send">
		</form>

【问题讨论】:

    标签: javascript jquery html ajax validation


    【解决方案1】:

    为对象属性设置值时,应将, 放在值之后,而不是;。所以把required: true;(三个地方)、email: true;改成required: true,email: true,

    然后你的代码就可以工作了,就像这里:fiddle

    【讨论】:

    • 太棒了!谢谢。无论如何,我可以为输入错误时出现的 JS 错误添加样式吗?
    • 当然。将 css 添加到类 .error。我在答案中更新了小提琴。
    • 我认为你宁愿使用submitHandler: function(){ ... },如果表单有效,它将在提交按钮点击时调用,启动ajax请求,然后在你得到的时候在ajax的success回调中显示成功表单来自服务器的肯定确认。
    • 提交表单后应该发生什么:1) 是否会重新加载页面或转到其他 URL,或者 2) 您是否希望保留当前页面并仅刷新其中的一部分?如果 (1) 则不需要 ajax。然后,您只需像往常一样提交表单并在新页面上显示成功或错误,该页面将作为对您在表单的action 属性中指定的 php 请求的响应。如果 (2) 您需要使用 ajax 发送表单;您将需要删除 action 属性以避免自动提交并创建 ajax 请求;这很容易 - jQuery ajax post.
    • 您的意思是延迟提交表单以向用户显示消息?如果您认为是,您可以使用event.preventDefault()
    猜你喜欢
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多