使用 jQuery 进行表单元素验证
Posted
技术标签:
【中文标题】使用 jQuery 进行表单元素验证【英文标题】:Form element validation using jQuery 【发布时间】:2020-09-18 00:48:41 【问题描述】:我正在尝试制作验证页面,当在文本框中输入文本时,我需要停止说“请填写表格”。我只需要验证文本框何时为空
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03@gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation()
if (name == "" || surname == "" || email == "" || comments == "")
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
else
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
</script>
【问题讨论】:
请不要试图绕过标题验证 - 如果它想要更长的标题,请尝试这样做而不是用拼写错误来破解它。 您的 sn-p 不工作。 您试图仅在页面加载时获取值......而不是在事件发生时。另外一个 jQuery 对象没有value
使用 val()
方法代替
我尝试过使用val()
,但还是一样...我该如何解决这个sn-p?
【参考方案1】:
您的代码显示错误,因为在您的最后一行中,您使用的是“cmets”而不是“Message”,setCustomValidity() 也接受一个带有错误消息的字符串或一个空字符串,为了使其正常工作,请考虑使用文档的检索元素的方法,此外,您需要添加 reportValidity() 以便您的代码看起来像这样
if (name == "" || surname == "" || email == "" || comments == "")
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
else
name.setCustomValidity('');
name.reportValidity()
您也可以考虑使用辅助函数来动态使用元素 id
更新: 你可以用这个它会工作的
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03@gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
input.setCustomValidity('Please fill out this field');
input.reportValidity();
else
input.setCustomValidity('');
input.reportValidity();
function validation()
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='')
$('#myform').submit();
</script>
【讨论】:
其他的呢,这里只有“name”起作用,还需要“message” 这里是在 jsfiddle jsfiddle.net/sven07/09x1pvuz/#&togetherjs=THa1lrw3LQ987654321@ 上测试和工作的代码 前一个仅适用于名称,我检查了链接,结果发现 html 中有所需的属性,这不是我想要的,我想使用 jQuery 进行验证 最后一个代码也可以正常工作,只需确保在所有元素上添加属性 required="required"【参考方案2】:使用 jquery 验证表单的最简单方法是使用 jquery validate。
我绝对建议您不要直接在表单发布网址中使用 mailto,因为垃圾邮件机器人和类似的东西可能会抓住您的表单并尝试使用它来发送垃圾邮件。我在我为客户创建的所有联系我们页面上添加了 jquery 验证和验证码。
$('#frmsendemail').validate( // Send Email Form
ignore: '.ignore',
rules:
seFullname:
required: true,
minlength: 2
,
seContact:
required: true,
phonesUK: true,
,
seMail:
required: true,
email: true
,
seMsg:
required: true
,
seCaptchaStatus:
required: function ()
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "")
return true;
else
return false;
,
messages:
seFullname:
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than 0 characters long.")
,
seContact:
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least 0 numbers.")
,
seMail:
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username@domain.com""
,
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
,
highlight: function (element)
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
,
unhighlight: function (element)
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
,
showErrors: function (errorMap, errorList)
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
,
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function ()
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result)
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error")
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries@cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm(
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons:
close: function ()
);
以上代码来自我为联系我们脚本创建的页面。该脚本使用 name= 属性设置页面上的所有输入,然后在不满足验证规则时为输入设置消息,突出显示和取消突出显示有错误的字段,在设置的 div 标签中显示错误消息,然后当表单有效时处理表单提交。 :)
【讨论】:
以上是关于使用 jQuery 进行表单元素验证的主要内容,如果未能解决你的问题,请参考以下文章