【问题标题】:jQuery email field validation some problemjQuery电子邮件字段验证一些问题
【发布时间】:2021-07-11 04:24:59
【问题描述】:

我想对表单域的电子邮件地址应用一些条件。电子邮件地址字段是可选的。条件是-

  1. 电子邮件字段为空时不显示任何错误。
  2. 但是只有当email字段有值+邮件格式不匹配时才会出现错误。

我用下面的 jQuery 代码做得很好。但这就是问题所在 - 当我应用此条件时 [ !$("#billing_email").val().match(/^\b[A-Z0-9._%-]+@[A-Z0 -9.-]+.[A-Z]{2,4}\b$/i ) ],即使email字段为空,邮件地址仍然是必填项!但邮件字段不是必需的。

我该如何解决这个问题?

$('form.checkout').on('submit', function () {
if ( $("#billing_email").val()!== '' && !$("#billing_email").val().match(/^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i )) {

  if ( $("#billing_email").parent().next(".error").val() !== '') {
    $("#billing_email").parent().after("<span class='error'>Invalid email...</span>");
    $("#billing_email").focus(); //Focus on field   
  }
} 

else {
  $("#billing_email").parent().next(".error").remove();
} 
});

【问题讨论】:

  • 您是否检查过电子邮件字段不包含任何空格?如果它包含任何空格,则在检查条件之前修剪值。
  • 请解释一下....
  • " "== "" 这个条件将在 js 中评估为 false,因为第一个字符串包含空格。现在 $("#billing_email").val() 将有任何空间然后 $("#billing_email").val() != "" 将返回 true 并且将检查第二个条件,这可能是 false 。所以试试$("#billing_email").val().trim() !== ''这样的条件
  • 不能正常工作...

标签: jquery woocommerce


【解决方案1】:

您的代码运行良好。我认为您可能需要添加:

$(this).find('.error').remove();

if 条件之前。

【讨论】:

  • 是的,代码运行良好。但是当电子邮件字段为空时,直到那里给出电子邮件才会提交。但电子邮件字段是可选的。删除这一行 "!$("#billing_email").val().match(/^\b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z] {2,4}\b$/i ) ]" 再次提交,但错误信息显示不正确!有什么想法..?
  • 检查元素中是否存在名为required的属性。如果是,则必须删除该属性才能通过浏览器验证。
  • 电子邮件地址字段是可选的。不需要
【解决方案2】:

我假设前端代码没有问题。您正在使用 woocommerce 对吗?你需要billing email address 作为可选。您需要在functions.php 中使用woocommerce_checkout_fields 钩子来设置不需要的billing email

add_filter( 'woocommerce_checkout_fields' , 'override_checkout_fields' );

function override_checkout_fields($fields) {
  $fields['billing']['billing_email']['required'] = false;
  return $fields;
}

【讨论】:

  • 是的,我正在使用 woocommerce。使用此过滤器,我已经将必填字段设为可选。我希望在字段中没有值时提交表单。错误也正确显示。
  • 能否提供您网站的链接或错误消息的屏幕截图?
【解决方案3】:

代码按预期工作。我只是对其进行了一些调整,使其更具可读性并具有更多“特定”条件。

查看下方

(我从提交更改为点击,所以我可以在不提交的情况下测试它,您可以将其更改回提交)

$('button').on('click', function() {
  const emailInput = $("#billing_email")
  const emailInputVal = $(emailInput).val()
  const emailInputParent = $(emailInput).parent()
  if (
    $(emailInputVal).trim().length > 0 &&
    !$(emailInputVal).match(/^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i)
  ) {

    if ($(emailInputParent).next(".error").length === 0) {
      $(emailInputParent).after("<span class='error'>Invalid email...</span>");
      emailInput.focus(); //Focus on field   
    }
  } else {
    $(emailInputParent).next(".error").remove();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkout">
  <span>
    <input id="billing_email" type="text">
  </span>

  <button type="submit">Submit</button>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2019-06-16
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多