2 回答
TA贡献1865条经验 获得超7个赞
试试这个:
onclick="validate(event)"
function validate(e){
e.preventDefault();
// Required first name
fname = document.getElementById("fname").value;
try{...
它会阻止你的表单采取行动。然后,您只需要处理函数内的重定向即可。
TA贡献1818条经验 获得超11个赞
将输入类型更改为按钮,因为您具有如下所示的onclick功能
断续器
<button id="submit" onclick="validate(event)">Submit</button>
断续器
添加了事件.prevent默认()
function validate(event){
event.preventDefault();
// Required first name
fname = document.getElementById("fname").value;
try{
if (fname == "") throw "You have not given your first name.";
}
catch(err) {
alert(err);
console.error(err);
}
// valid date format
bdate = document.getElementById("bdate").value;
var contains = bdate.indexOf("/");
var day = bdate.slice(0, 2);
var month = bdate.slice(3);
try{
if (contains != 2 && bdate !== "") throw "The date must be in the following format 'dd/mm' to be valid.";
if (isNaN(day) || isNaN(month) && bdate !== "") throw "The date must contain numbers.";
if (day > 31 && bdate !== "") throw "You seem to have done a typo with your birth day.";
if (month > 12 && bdate !== "") throw "You seem to have done a typo with your birth month.";
}
catch(err) {
alert(err);
console.error(err);
}
// Valid email address
email = document.getElementById("email").value;
var searchAt = email.indexOf("@");
var searchDot = email.indexOf(".");
try{
if (email == "") throw "You have not given your email.";
if (searchAt == -1) throw "Your email must contain an '@' symbol.";
if (searchDot == -1) throw "Your email must contain a . ";
}
catch(err){
alert(err);
console.error(err);
}
};
添加回答
举报