jquery 提交表单时HTML模式不起作用

2cmtqfgy  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(103)

案例一

我有以下工作如预期。当单击“button”时,提交表单并验证模式。

<input autocomplete="off" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
        type="text" id="username" name="username" required class="form-control"
        value="${loginForm.username}" placeholder="Email"/>

<button type="submit" id="submitButton" name="forgotUsernameBtn" class="submit butn-blue butn-md butn">
    Forgot Username
</button>

字符串

案例二

然而,我有一个不同的情况,我需要首先调用一个函数(verifyCaptcha()),然后提交表单,在这种情况下,电子邮件上的模式验证没有发生。

function verifyCaptcha(){
    console.log('verifying captcha');
    if (typeof grecaptcha !== 'undefined') {
        var siteKey = 'xxxx';
        grecaptcha.execute(siteKey, {action: 'forgotPassword'}).then(function(response) {
            console.log(response);
            $('#response').val(response);
            $('#loginFormBean').submit();
        });
    }
    return false;
}

<button type="button" id="submitButton"  value="Submit" class="submit butn butn-blue butn-md" onclick="verifyCaptcha()">Submit</button>


这是因为在Case1中,它是通过button type="submit"提交的,而在Case2中,它只通过Jquery $('#loginFormBean').submit();在函数中提交。

问题

是否可以获取Case2进行模式验证?

xwbd5t1u

xwbd5t1u1#

这里我有一个表单上提交事件的事件监听器。仅当所有表单域都有效时,才会发生此事件。事件侦听器的回调函数定义为async,并有一个e.preventDefault()来阻止表单提交。现在我可以在函数调用grecaptcha.execute()之前使用await。函数调用的响应最终会返回(这里我假装2秒),脚本继续执行。如果响应是OK,我调用e.target.submit()来“恢复”提交。
我的伪模块的默认行为是返回true。因此,示例将始终在表单有效时提交。

// fake module to for testing
// change "true" to "false" to let the captcha fail.
const grecaptcha = (() => {
  return {
    async execute(key, obj) {
      return new Promise(resolve => {
        setTimeout(() => {resolve(true);}, 2000);
    });
    }
  }
})();

document.forms.form01.addEventListener('submit', async e => {
  e.preventDefault();
  if (typeof grecaptcha !== 'undefined') {
    let siteKey = 'xxxx';
    let validCaptcha = await grecaptcha.execute(siteKey, {
      action: 'forgotPassword'
    });
    console.log(validCaptcha);
    if(validCaptcha){
      console.log('Submitting...');
      e.target.submit();
    }else{
      console.log('Captcha not ok');
    }
  } else {
    console.log('No grecaptcha');
  }
});

个字符

相关问题