如果字段验证没有错误,我正在尝试验证表单中的字段,并在用户单击提交按钮时拉出不同的 html 文件。
- 但是,验证器似乎不起作用。我希望"事件名称"和"位置"字段为字母数字字符和空格,但它似乎也采用其他值。
- 将onClick="self.location='successPage.html'">放在提交按钮中似乎也不能验证字段。如果表单中的所有字段都已成功验证,我希望它移动到 successPage.html 文件。
我不想使用jQuery。
这是我的代码:
<form action="" >
<p>
<label>
Day of the week:<br>
<select name="days">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select><br>
</label>
<label>
Start Time:<br>
<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
</label>
<label>
End Time:<br>
<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
</label>
<label>
Event Name:<br>
<input id="ename" type="text" name="ename" required /><br>
</label>
<label>
Location:<br>
<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9s]"-->
</label>
<label>
Enter URL for the pictture:<br>
<input id="urlpic" type="text" name="urlname" />
</label>
<br><br>
<input type="reset" id="reset" value="Reset" />
<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
</p>
</form>
<script>
function chkName() {
var myName = documnet.getElementById("ename");
var pos = myName.value.search( /^[A-Za-z0-9s]/);
if (pos != 0) {
alert("Please check your input (" + myName + ") again");
return false;
} else
return true;
}
function chkLoc() {
var myLoc = documnet.getElementById("loc");
var pos = myLoc.value.search( /^[A-Za-z0-9s]/);
if (pos != 0) {
alert("Please check your input (" + myLoc + ") again");
return false;
} else
return true;
}
document.getElementById("ename").onchange = chkName;
document.getElementById("loc").onchange = chkLoc;
</script>
<form action="." method="POST" onsubmit="return validate(this)">
<input type="submit" value="Submit">
</form>
表单元素将在用户提交时传递到 Verify 函数中,返回 false 表示不提交表单,返回 true 表示提交表单。
<script>
function validate(form) {
console.log(form); // log element to console on submit
return false; // replace with true if input is good to be submitted
}
</script>