您能帮我提供上面的代码吗?
我',试图在其中进行一些验证,但是没有执行验证,并且在没有验证的情况下提交了表单:
HTML:
<form method="post" action="" id="subscription-form">
<div class="form-group">
<input class="subscribe-email" type="email" name="email" placeholder="youremail@example.com" required>
<p><span class="error-message">Please enter a valid email</span></p>
</div>
<button id="" class="" type="submit"><span>Subscribe</span></button>
</form>
JS:
$(document).ready(function() {
$('#subscription-form').on('submit', function (e) {
var form = $(this);
var regexEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var url = "https://mycustomapi.net";
if (!$('.subscribe-email').val().match(regexEmail)) {
$('.error-message').hide();
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function (data) {
$('#subscribed-error').hide()
$('#subscribed-feedback').show()
$('#subscription-form').hide()
},
error: function () {
$('#subscribed-error').show()
$('#subscribed-feedback').hide()
$('#subscription-form').show()
}
});
console.log('email submitted');
e.preventDefault();
return false;
}
else {
$('.error-message').show();
e.preventDefault();
return false;
}
});
});
谢谢
答案 0 :(得分:1)
您的错误是!运算符
$(document).ready(function() {
$('#subscription-form').on('submit', function (e) {
var form = $(this);
var regexEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
var url = "https://mycustomapi.net";
if ($('.subscribe-email').val().match(regexEmail)) {
$('.error-message').hide();
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function (data) {
$('#subscribed-error').hide()
$('#subscribed-feedback').show()
$('#subscription-form').hide()
},
error: function () {
$('#subscribed-error').show()
$('#subscribed-feedback').hide()
$('#subscription-form').show()
}
});
console.log('email submitted');
e.preventDefault();
return false;
}
else {
console.log("not submitted");
$('.error-message').show();
e.preventDefault();
return false;
}});
});
<form method="post" action="" id="subscription-form">
<div class="form-group">
<input class="subscribe-email" type="text" name="email" placeholder="youremail@example.com" required>
<p><span class="error-message">Please enter a valid email</span></p>
</div>
<button id="" class="" type="submit"><span>Subscribe</span></button>
</form>