Jquery循环为表单验证输出错误的错误信息

Posted

技术标签:

【中文标题】Jquery循环为表单验证输出错误的错误信息【英文标题】:Jquery loop outputting the wrong error message for form validation 【发布时间】:2020-04-19 23:01:23 【问题描述】:

我无法设置正确的表单验证条件。

第 46 行:if (input.value == '' && mail_type_selector.val() == null)

如果未选择邮件类型,仅填写最后一个输入(邮件宽度),其余输入为空。它仍然应该输出 错误信息:“请填写必填字段并选择邮件类型”

但它从第 34 行的条件中输出消息“请选择邮件类型”。

如果仅填充最后一个输入字段而其余输入字段为空,如何确保 jquery 每个循环将输出第 46 行条件中的错误消息?

/* ==========================================================================
                               DOM Elements
    ========================================================================== */
const error_msg_section = $('#error_msg_section');
const mail_type_selector = $('#mail_type_selector');


/* ==========================================================================
                                Validate form
    ========================================================================== */


function checkForm() 
  let error_msg_text = '';
  let is_form_valid = true;


  $('form input[required]:visible').each(function(index, input) 

    let input_name = $(this).attr('name');
    let input_label = $(this).prev('label');

    // Check if a field has no value
    if (input.value === '') 

      // Add class to inputs label to indicate that it has no value
      input_label.addClass('empty-input');

      error_msg_text = 'Please fill out the required field(s)';

     else input_label.removeClass('empty-input');


    // Check if a mail  type is not selected
    if (mail_type_selector.val() === null) 

      mail_type_selector.addClass('error-option-not-selected');

      error_msg_text = 'Please select a mail type';

     else mail_type_selector.removeClass('error-option-not-selected');



    // Check if a field has no value and if a mail type is not selected
    if (input.value == '' && mail_type_selector.val() == null) 

      error_msg_text = 'Please fill out the required field(s) and select a mail type';

      mail_type_selector.addClass('error-option-not-selected');
    


    // Append the error message to the error section paragraph
    error_msg_section.text(error_msg_text);

    // Check if the element contains an error message
    if (error_msg_section.text() !== '') 

      is_form_valid = false; // Set to false to indicate that the form is invalid
      error_msg_section.addClass('display-error-msg'); // Display the error message on the UI

     else 
      error_msg_section.removeClass('display-error-msg');
    
  );


return is_form_valid;



/* ==========================================================================
                            Send Form
========================================================================== */

$('.destinations button').click(function(e) 


  e.preventDefault();

  checkForm()
)

console.log('test')
form 
  display: grid;
  column-gap: 1em;
  grid-template-columns: 1fr 1fr;


form>section 
  border-radius: 5px;
  padding: 4px 15px 10px 15px;
  border: 1px solid #00000061;


.input-fields 
  display: grid;
  row-gap: 1em;


.input-fields>div 
  display: grid;


.input-fields>div>label 
  margin-bottom: 3px;
  font-size: 14px;



.shipping-info .input-fields,
button 
  margin-top: 15px;



.input-fields label.empty-input 
  color: red;


#error_msg_section 
  text-align: center;
  margin-top: 10px;
  color: red;
  display: none;


#error_msg_section.display-error-msg 
  display: block;



select.error-option-not-selected 
  border-color: red;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<form>

  <section class="destinations">
    <p>Destination</p>

    <div class="input-fields">

      <div>
        <label for="city">City</label>
        <input type="text" id="city" name="city" required>
      </div>

      <div>
        <label for="state">State</label>
        <input type="text" id="state" name="state" required>
      </div>

      <div>
        <label for="zip">Zip</label>
        <input type="text" id="zip" name="zip" required>
      </div>

      <div>
        <select>
          <option disabled selected>Please select a country</option>
          <option>US</option>
          <option>CA</option>
        </select>
      </div>

    </div>

    <button>Send</button>
  </section>

  <section class="shipping-info">
    <p>Shipping information</p>

    <select id="mail_type_selector">
      <option disabled selected>Please select a mail type</option>
      <option>Letter</option>
      <option>Package</option>
    </select>

    <div class="input-fields">

      <div>
        <label for="mail_weight">Mail weight</label>
        <input type="text" id="mail_weight" name="mail_weight" required>
      </div>

      <div>
        <label for="mail_length">Mail length</label>
        <input type="text" id="mail_length" name="mail_length" required>
      </div>

      <div>
        <label for="mail_height">Mail height</label>
        <input type="text" id="mail_height" name="mail_height" required>
      </div>

      <div>
        <label for="mail_width">Mail width</label>
        <input type="text" id="mail_width" name="mail_width" required>
      </div>

    </div>
  </section>

</form>

<p id="error_msg_section"></p>

【问题讨论】:

How do I ask a good question? 【参考方案1】:

我会将检查 mail_type_selector 是否有值的逻辑移到每个循环之外,即

/* ==========================================================================
                               DOM Elements
    ========================================================================== */
const error_msg_section = $('#error_msg_section');
const mail_type_selector = $('#mail_type_selector');


/* ==========================================================================
                                Validate form
    ========================================================================== */


function checkForm() 
  let error_msg_text = '';
  let is_form_valid = true;


  $('form input[required]:visible').each(function(index, input) 

    let input_name = $(this).attr('name');
    let input_label = $(this).prev('label');

    // Check if a field has no value
    if (input.value === '') 

      // Add class to inputs label to indicate that it has no value
      input_label.addClass('empty-input');

      error_msg_text = 'Please fill out the required field(s)';

     else input_label.removeClass('empty-input');
  );

  // Check if a mail  type is not selected
  if (mail_type_selector.val() === null) 
    // Check if any of the input fields have already triggered a validation message
    if (error_msg_text) 
      error_msg_text = 'Please fill out the required field(s) and select a mail type';
      mail_type_selector.addClass('error-option-not-selected');
     else 
      mail_type_selector.addClass('error-option-not-selected');
      error_msg_text = 'Please select a mail type';
    
   else mail_type_selector.removeClass('error-option-not-selected');

  // Append the error message to the error section paragraph
  error_msg_section.text(error_msg_text);

  // Check if the element contains an error message
  if (error_msg_section.text() !== '') 
    is_form_valid = false; // Set to false to indicate that the form is invalid
    error_msg_section.addClass('display-error-msg'); // Display the error message on the UI

   else 
    error_msg_section.removeClass('display-error-msg');
  

  return is_form_valid;



/* ==========================================================================
                            Send Form
========================================================================== */

$('.destinations button').click(function(e) 


  e.preventDefault();

  checkForm()
)

console.log('test')
form 
  display: grid;
  column-gap: 1em;
  grid-template-columns: 1fr 1fr;


form>section 
  border-radius: 5px;
  padding: 4px 15px 10px 15px;
  border: 1px solid #00000061;


.input-fields 
  display: grid;
  row-gap: 1em;


.input-fields>div 
  display: grid;


.input-fields>div>label 
  margin-bottom: 3px;
  font-size: 14px;


.shipping-info .input-fields,
button 
  margin-top: 15px;


.input-fields label.empty-input 
  color: red;


#error_msg_section 
  text-align: center;
  margin-top: 10px;
  color: red;
  display: none;


#error_msg_section.display-error-msg 
  display: block;


select.error-option-not-selected 
  border-color: red;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<form>

  <section class="destinations">
    <p>Destination</p>

    <div class="input-fields">

      <div>
        <label for="city">City</label>
        <input type="text" id="city" name="city" required>
      </div>

      <div>
        <label for="state">State</label>
        <input type="text" id="state" name="state" required>
      </div>

      <div>
        <label for="zip">Zip</label>
        <input type="text" id="zip" name="zip" required>
      </div>

      <div>
        <select>
          <option disabled selected>Please select a country</option>
          <option>US</option>
          <option>CA</option>
        </select>
      </div>

    </div>

    <button>Send</button>
  </section>

  <section class="shipping-info">
    <p>Shipping information</p>

    <select id="mail_type_selector">
      <option disabled selected>Please select a mail type</option>
      <option>Letter</option>
      <option>Package</option>
    </select>

    <div class="input-fields">

      <div>
        <label for="mail_weight">Mail weight</label>
        <input type="text" id="mail_weight" name="mail_weight" required>
      </div>

      <div>
        <label for="mail_length">Mail length</label>
        <input type="text" id="mail_length" name="mail_length" required>
      </div>

      <div>
        <label for="mail_height">Mail height</label>
        <input type="text" id="mail_height" name="mail_height" required>
      </div>

      <div>
        <label for="mail_width">Mail width</label>
        <input type="text" id="mail_width" name="mail_width" required>
      </div>

    </div>
  </section>

</form>

<p id="error_msg_section"></p>

为了简化验证,我建议使用 jQuery 验证 (https://jqueryvalidation.org/) 等库。

【讨论】:

谢谢!!它就像一个魅力!好的,我一定会检查出来

以上是关于Jquery循环为表单验证输出错误的错误信息的主要内容,如果未能解决你的问题,请参考以下文章

jQuery插件Validate验证提交表单submitHandler更改错误信息显示的位置requiredValidator内置验证方式表validate ()的可选项汇总

018输出错误信息与调试信息

web.xml配置错误页面,及输出错误信息

如何让log4j日志只输出错误信息

jQuery 表单验证检查以循环结束

为什么暂时性死区代码执行输出错误信息不是x is not defined?