JavaScript validation and cookies
JavaScript validation and cookies
我目前在一个JavaScript类中,我的最后一项任务是编写一个代码来验证预订请求表单并创建cookie。我在作业中得到了一半的学分,因为我的代码没有100%正确工作,我知道情况确实如此。代码中发生的情况是,当我在没有将信息放入文本框的情况下刷新页面时,它会对我大喊"此信息是必需的",但当我填写了一些必需的信息并将其余部分留空时,它仍然会转到"谢谢你的请求"页面。
这是我的javascript代码:
$(document).ready(function() {
var emailPattern = /'b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+'.[A-Za-z]{2,4}'b/;
$(":text, #arrival_date, #nights, #name, #email, #phone").after("<span class='error'>*</span>");
$("#reservation_form").submit(
function(event) {
var isValid = true;
$("#arrival_date").focus();
// validate the requested arrival date
if ($("#arrival_date").val() == "") {
$("#arrival_date").next().text("This field is required.");
isValid = false;
}
else {
// store arrival date in cookie wds 7/13/2013
setCookie("guestdate",$("#arrival_date").val(),365);
$("#arrival_date").next().text("");
}
// validate the requested arrival nights
if ($("#nights").val() == "") {
$("#nights").next().text("This field is required.");
isValid = false;
}
else {
setCookie("guestnights",$("#nights").val(),365);
$("#nights").next().text("");
}
// validate the requested name
if ($("#name").val() == "") {
$("#name").next().text("This field is required.");
isValid = false;
}
else {
setCookie("guestname",$("#name").val(),365);
$("#name").next().text("");
}
// validate the requested email
if ($("#email").val() == "") {
$("#email").next().text("This field is required.");
isValid = false;
}
else {
setCookie("guestemail",$("#email").val(),365);
$("#email").next().text("");
}
// validate the requested phone number
if ($("#phone").val() == "") {
$("#phone").next().text("This field is required.");
isValid = false;
}
else {
setCookie("guestphone",$("#phone").val(),365);
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
}
} // end function
); // end submit
}); // end ready
我的教授从来没有告诉我我做错了什么,下周我还有一项与此非常相似的作业。她在我的反馈中只说"我看到了验证代码,但当我运行程序时,这些代码都不起作用"。作业结束后,她也不公布答案,这很令人沮丧。任何帮助都将是美妙的!
检查此更新的fiddle。https://jsfiddle.net/xjr3ro6k/4/当使用jquery验证插件时,您可以将规则传递给表单选择器验证方法,如下所示:
$( "#reservation_form" ).validate({
rules: {
field: {
required: true
}
}
});
或者,您可以简单地在该特定标记中添加required,并像本例中那样向表单选择器运行validate方法http://jqueryvalidation.org/files/demo/你可以浏览这些演示并了解更多关于这个插件的信息。
继续学习。
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- angularjs中$cookiestore和$cookies之间的差异
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- Chrome Extensions and Cookies
- JavaScript validation and cookies
- Cookies is html and javascript
- Cookies & URL's and instances
- Ajax and cookies
- (Javascript) Div toggle and cookies
- HTML5 - localStorage, Cookies, and SQL
- jquery cookies and Legend state
- PhantomJS persistent cookies and Javascript