【发布时间】:2019-11-15 01:44:55
【问题描述】:
我似乎无法找出正确的 JavaScript 来验证此表单。请帮助/提供反馈!
基本上,我的脚本应该验证用户是否在输入文本框中输入了数据,是否选中了一个单选按钮,是否选中了至少一个复选框,以及是否从所选项目中选择了一个选项。
此外,表单使用提交按钮来调用验证脚本,以便仅在表单字段被验证和接受时才处理表单。如果某个字段无效,则向用户显示一条消息。
还需要确保表单不会在每次用户收到验证错误时自动重置。
<body>
<section>
<h1 style="text-align: center">Vacation Interest Vote Form</h1>
<form name="VacayForm" action="mailto:" onsubmit="return Validate1()" method="post">
<p>Name:<input type="text" name="name" size="25"></p><br>
<p>Do You Prefer an international destination?</p>
<p>Domestic<input type="radio" name="domint" value="domestic"></p>
<p>International<input type="radio" name="domint" value="international"></
<br>
<p>Where would you like to go?</p>
<select type="text" name="continent" value="select" size="1">
<option value="domestic">Domestic</option>
<option value="europe">Europe</option>
<option value="camerica">Central America</option>
<option value="asia">Asia</option>
<option value="aus">Australia</option>
</select>
<br>
<p>Check the box to act as your digital signature to cast your vote
<input type="checkbox" value="agree" name="sig">
<input type="submit" value="Send" name="submit" onclick="if(!this.form.sig.checked){alert('You must agree to cast your vote by checking the box.');
return false}">
<input type="reset" value="Reset"name="reset">
</form>
</section>
<script>
function Validate1() {
var nam = document.forms["VacayForm"]["name"];
var dom = document.forms["VacayForm"]["domestic"];
var int = document.forms["VacayForm"]["international"];
var sel = document.forms["VacayForm"]["select"];
var agree = document.forms["VacayForm"]["agree"];
//if (name.value == "")
//{
// window.alert("Please enter your name.");
// name.focus();
// return false;
//}
if( document.VacayForm.name.value == "" )
{
alert( "Please provide your name!" );
document.VacayForm.name.focus() ;
return false;
}
if (domestic.value == "")
else (international.value == "")
{
window.alert("Please select domestic or international preference to proceed.");
domestic.focus();
international.focus();
return false;
}
if (select.selectedIndex < 1)
{
alert("Please select where you prefer to visit");
select.focus();
return false;
}
return true;
}
//function Validate2() {
// var radios = document.getElementsByName("yesno");
// var formValid = false;
// var i = 0;
// while (!formValid && i < radios.length) {
// if (radios[i].checked) formValid = true;
// i++;
// }
// if (!formValid) alert("Must check an option!");
// return formValid;
//}
</script>
</body>
</html>
【问题讨论】:
-
当问题与 jQuery Validate 插件完全无关时,请不要使用 jQuery Validate 标签。已编辑。
-
只要有JS,我也可以使用Jquery validate。因此我使用它的原因......我希望你在要求我自己做之前不要自己编辑我的帖子。
-
That's not how it works around here。标签用于根据内容对问题进行分类,鼓励任何有权编辑帖子的人根据需要这样做。由于问题不是询问 jQuery Validate 插件,也不包含任何与 jQuery Validate 插件相关的代码,因此“jQuery Validate”标签在这里绝对不合适。谢谢。
标签: javascript forms validation