问题描述
我正在尝试使用 ajax 提交执行表单验证功能。由于某种原因验证不起作用,当它提交时,我的服务器获取空字段(当我测试验证时)但它表明它试图发布到同一页面......我不知道为什么.
表格:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<form id='form' novalidate method="post" class='m-2 p-1'>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="text" name='First Name' class="form-control" id="fname" placeholder="First Name">
<label for="fname">First Name<span class='red' aria-label='required'> *</span></label>
</div>
</div>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="text" name='Last Name' class="form-control" id="lname" placeholder="Last Name">
<label for="lname">Last Name</label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="email" name='Email' class="form-control" id="email" placeholder="Email">
<label for="lname">Email <span class='red' aria-label='required'> *</span></label>
</div>
</div>
<div class='col p-1'>
<div class="form-floating mb-3">
<select required name='Reason For Contacting' class="form-control" id="reason" placeholder="Reason For Contacting">
<option value='Feedback' selected>Feedback</option>
<option value='other'>Other</option>
</select>
<label for="why">Reason For Contacting<span class='red' aria-label='required'> *</span></label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<textarea required name='Comments' class="form-control" id="comment" placeholder="Your Comments"></textarea>
<label for="comment">Your Comments<span class='red' aria-label='required'> *</span></label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<button class='form-control btn btn-outline-primary' id='submit'>Send</button>
</div>
</div>
</form>
我的 JS 文件:
$(document).ready(() => {
autosize($('textarea'))
$('#submit').click((e) => {
if (validate() == true) {
sendForm();
} else {
error(validate())
}
})
})
var errors;
window.onerror = function(msg,url,linenumber) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
return true;
}
function validate() {
elements = $(':input')
elements.each((element) => {
element = $(element).get()
if (element.value === '' || !email(element)) {
errors += element.name + " is invalid."
} else {
return;
}
})
if (errors) {
return errors
} else true;
}
function sendForm() {
name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim()
email = $('input[name="Email"]').val().trim()
why = $("select").val().trim()
comments = $('textarea').val().trim()
data = {
"name": name,"email": email,"reason": why,"text": comments
}
$.ajax({
type: 'POST',url: 'https://admin.bekesbikes.tk/contact',crossDomain: true,data: data,dataType: 'json',success: (responseData,textStatus,errorThrown) => {
new Notify({
title: 'Submitted!',text: 'Your Feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',effect: 'slide',status: 'success',speed: 1000,autoclose: true
})
$(':input').val('');
$('select').val('Feedback')
},error: (responseData,errorThrown) => {
new Notify({
title: 'Could not submit!',text: 'The form Could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",status: 'error',autoclose: true
})
}
});
}
function error(text) {
new Notify({
title: 'Form Fields Are Not Correct',text: text,status: 'info',autoclose: true
})
}
function send() {
if (validate()) {
sendForm()
} else {
error(validate())
}
}
function email(element) {
if (element.type === 'email' && /^[^\s@]+@[^\s@]+$/.text(element.value)) {
return true;
} else if (element.type !== 'email') {
return true;
} else {
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
知道我应该做什么吗?
请注意,我将 node.js
与 express.js
一起使用。
编辑
我在提交事件处理程序中添加了:e.preventDefault()
,但是现在当我提交表单而不填写任何内容时,我收到以下通知:
解决方法
我更改了您的点击处理程序:
- 默认预防,
- validate() 作为变量,使其只运行一次,
错误声明
- 空字符串而不是未定义,
你的validate()函数
- 使用 :not() 排除按钮,
- 将箭头函数改为普通匿名函数,
- 使用 this 而不是元素,它只是一个索引,
- 添加了到最后一个 else 的返回,
和你的 email() 函数
- 将电子邮件验证外包给自己的函数。
我也删除了send(),因为它没有被使用,用var声明sendForm()中的变量并添加了许多分号->可能在你的代码中已经缺少一个,你希望js纠错会添加他们自动...
最后,我将参数 showIcon 添加到您的 Notify 对象(即“未定义”部分;)
$(document).ready(() => {
autosize($('textarea'))
$('#form').submit((e) => {
e.preventDefault();
var validated = validate();
if (validated == true) {
sendForm();
} else error(validated);
});
var errors = '';
window.onerror = function(msg,url,linenumber) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
return true;
}
function validate() {
elements = $(':input:not(button)');
elements.each(function() {
if (this.value === '' || !email(this)) {
errors += this.name + " is invalid.";
} else return;
});
if (errors) {
return errors;
} else return true;
}
function sendForm() {
var name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim();
var email = $('input[name="Email"]').val().trim();
var why = $("select").val().trim();
var comments = $('textarea').val().trim();
var data = {
"name": name,"email": email,"reason": why,"text": comments
};
$.ajax({
type: 'POST',url: 'https://admin.bekesbikes.tk/contact',crossDomain: true,data: data,dataType: 'json',success: (responseData,textStatus,jqXHR) => {
new Notify({
title: 'Submitted!',text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',effect: 'slide',status: 'success',speed: 1000,autoclose: true,showIcon: false
});
$(':input').val('');
$('select').val('Feedback');
},error: (jqXHR,errorThrown) => {
new Notify({
title: 'Could not submit!',text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",status: 'error',showIcon: true
});
}
});
}
function error(text) {
new Notify({
title: 'Form Fields Are Not Correct',text: text,status: 'info',showIcon: false
})
}
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function email(element) {
if (element.type === 'email' && validateEmail(element.value)) {
return true;
} else if (element.type !== 'email') {
return true;
} else return false;
}
});