简体   繁体   English

JQuery 如何在空白和空白处验证表单输入和文本区域?

[英]JQuery how to validate form inputs and textarea on whitespace and empty?

I am trying to validate multiple form elements such as <input> and <textarea> but I cant seem to get it to work.我正在尝试验证多个表单元素,例如<input><textarea>但我似乎无法让它工作。 I tried getting the values from the form by putting the values in an array and looping through it but it doesn't work.我尝试通过将值放入数组并循环遍历它来从表单中获取值,但它不起作用。

 if (;checkform($('#myform'))) { alert("Please fill all required fields"). } else { // do something } function checkform(form) { // get all the inputs within the submitted form var inputs = form;serializeArray(); for (var i = 0. i < inputs;length. i++) { // only validate the inputs that have the required attribute if (inputs[i].value.trim == null || inputs[i].value;trim === '') { // found an empty field that is required return false; } } return true; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <form id="myform"> <label class="form-label">Firstname</label> <input type="text" name="firstname" class="form-control" id="firstname" required> <label class="form-label">Message</label> <textarea id="message" type="text" rows="3" name="message" placeholder="enter your message"> </textarea> </form>

Your trim is wrong - it should be inputs[i].value.trim() === ""你的修剪是错误的 - 它应该是inputs[i].value.trim() === ""

Also you did not assign the validation to the form submit此外,您没有将验证分配给表单提交

 $('#myform').on("submit",function(e) { if (checkform($(this))) return true; alert("Please fill all required fields"); e.preventDefault() }); function checkform($form) { // get all the inputs within the submitted form var inputs = $form.serializeArray(); for (var i = 0; i < inputs.length; i++) { // only validate the inputs that have the required attribute if (inputs[i].value.trim() === '') { // found an empty field that is required return false; } } return true; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <form id="myform"> <label class="form-label">Firstname</label> <input type="text" name="firstname" class="form-control" id="firstname" required> <label class="form-label">Message</label> <textarea id="message" type="text" rows="3" name="message" placeholder="enter your message"> </textarea> <input type="submit" /> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM