首页 > 解决方案 > 如果使用带有 RegEx 的 Jquery 电子邮件无效,则禁用提交按钮

问题描述

您能否向我展示一些在带有 RegEx 的电子邮件无效时禁用提交按钮的示例?如果您的答案或解释很简单,以便新手可以像我一样理解,那就太好了:)

谢谢

标签: jqueryregex

解决方案


只需在输入字段上添加事件即可触发验证功能。

如果emailRegex不匹配,将disabled属性设置为提交按钮。否则删除该属性

// Start script when everything is loaded
$(document).ready(function() {
  // Email regex. It's very generic: check if "@" is present and has ".abc" end.
  // There is no 100% correct email regex.
  var emailRegex = /\w+@\w+\.\w{3}/;

  // Add event to be triggered on input field change
  $('#email').on('change', function() {
    // Disable or enable submit button depending on regex validation
    $('#submit').prop('disabled', emailRegex.test($(this).val()) == false);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<input type="text" placeholder="Email" id="email"/>

<button id="submit">Submit</button>


推荐阅读