1

我很好奇如何强制用户输入有效的电子邮件地址,如果它无效,不将提交按钮显示为活动状态?

这是我拥有的当前代码。目前,如果电子邮件无效,它会显示红色边框,但用户仍然可以单击提交按钮。

$("button[type='submit']").on('click', function () {

        $(".error").hide();
        let hasError = false;

        let emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        let emailAddressVal = $("#user_email").val();
        if (emailAddressVal == ''){
            $("#user_email").after('<span class="error">Please enter your email address.</span>');
            hasError = true;
        }

        else if(!emailReg.test(emailAddressVal)) {
            $("#user_email").after('<span class="error">Enter a valid email address.</span>');
            hasError = true;
        }

        //alert(emailAddressVal);

        if(hasError == true) {
            return false;
        }


    })

这是输入输入的位置:

        <div class="col-md-3">
            <i class="fas fa-envelope fa-lg"></i>
            <label data-error="wrong" data-success="right">Enter your email</label>
            <input type="email" class="form-control validate purple-border" id="user_email">

        </div>

这是提交按钮:

<button type="submit" class="btn btn-purple purple-border">Perform Frame Classification</button>

在此处输入图像描述

4

1 回答 1

1

与其在提交按钮上使用click事件来检查电子邮件,不如在用户键入时检查它(在keyup事件上),并使用测试结果来启用按钮(请注意,我们从禁用按钮开始):

$("#user_email").on('keyup', function() {
  $(".error").hide();
  let hasError = false;

  let emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

  let emailAddressVal = $(this).val();
  if (emailAddressVal == '') {
    $("#user_email").after('<span class="error">Please enter your email address.</span>');
    hasError = true;
  } 
  else if (!emailReg.test(emailAddressVal)) {
    $("#user_email").after('<span class="error">Enter a valid email address.</span>');
    hasError = true;
  }

  $('button[type="submit"]').prop('disabled', hasError);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-3">
  <i class="fas fa-envelope fa-lg"></i>
  <label data-error="wrong" data-success="right">Enter your email</label>
  <input type="email" class="form-control validate purple-border" id="user_email">

</div>


<button type="submit" class="btn btn-purple purple-border" disabled="disabled">Perform Frame Classification</button>

于 2020-06-17T00:00:04.463 回答