简体   繁体   English

onsubmit不触发验证功能

[英]onsubmit does not trigger validate function

I'm trying to write some code to validate data submitted in a HTML form. 我正在尝试编写一些代码来验证以HTML表单提交的数据。 However when I click the submit button the validation function doesn't run and the form is submitted. 但是,当我单击“提交”按钮时,验证功能无法运行,并且表单已提交。

function validate() {
    "use strict";

    var errMsg = "";
    var result = true;

    var firstname = document.getElementById("firstname").value;

    if (!firstname.match(/^[a-zA-Z]+$/)) {
        errMsg = errMsg + "your first name must only contain alpha characters\n";
        result = false;
    }

    return result;
}


function init() {
    "use strict";

    var regForm = document.getElementById("submit");
    regForm.onsubmit = validate;

}

window.onload = init;

I made sure that the code was running by throwing in an alert and sure enough it worked. 我通过发出警报来确保代码正在运行,并确保它可以正常工作。 I'm having trouble seeing where the validation code is going wrong? 我在查看验证码哪里出问题时遇到了麻烦?

Note: I have to keep the JavaScript separate from the HTML. 注意:我必须将JavaScript与HTML分开。

I'm gonna guess: 我猜:

var regForm = document.getElementById("submit");

if the id='submit' element is your submit button and not the form then that could be the issue. 如果id ='submit'元素是您的提交按钮,而不是表单,则可能是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM