Html 如何在表单提交上调用两个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16250915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:56:05  来源:igfitidea点击:

How to call two functions on a form submit

javascripthtmlformsfunction

提问by entropy

I am trying to do javascript form validation, and to do this I need to call two functions. One for the password and on for the username (I will also need to call more later on).

我正在尝试进行 javascript 表单验证,为此我需要调用两个函数。一个用于密码,一个用于用户名(稍后我还需要调用更多)。

Here is my JS code:

这是我的 JS 代码:

function validateUserName(NewUser)
{
    var u = document.forms["NewUser"]["user"].value
    var uLength = u.length;
    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if (u == null || u == "")
    {
        alert("You left Username field empty");
        return false;
    }
    else if (uLength <4 || uLength > 11)
    {
        alert("The Username must be between 4 and 11 characters");
        return fasle;
    }
    else if (illegalChars.test(u)) 
    {
        alert("The username contains illegal characters");
        return false;
    }
    else
    {
        return true;
    }
}

function validatePassword(pwd, confirmPwd)
{
    var p = document.forms["NewUser"]["pwd"].value
    var cP = document.forms["NewUser"]["cP"].value
    var pLength = p.length;
    if (p == null || p == "")
    {
        alert("You left the password field empty");
        return false;
    }
    else if (pLength < 6 || pLength > 20)
    {
        alert("Your password must be between 6 and 20 characters in length");
        return false;
    }
    else if (p != cP)
    {
        alert("Th passwords do not match!");
        return false;
    }
}

and here is my HTML form:

这是我的 HTML 表单:

<form name = "NewUser" onsubmit= "return validateUserName(), return validatePassword()" action = "">
                <tr>
                <td>Username:</td> 
                <td><input type = "text" name = "user"/></td> 
                </tr>
                <tr>
                <td class = "Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
                </tr>

                <tr>
                <td>Password:</td>
                <td><input type = "password" name = "pwd"/></td>
                <tr>
                <td  class = "Information"><em>6-20 characters</em></td>
                </tr>

                <tr>
                <td>Confirm Password:</td>
                <td><input type = "password" name = "confirmPwd"/></td>
                <tr>
                <td  class = "Information"><em>just in case you didn't make mistakes!</em></td>
                </tr>

            <input type = "submit" value = "Submit"/>

Please ignore the table code.

请忽略表格代码。

Should I rather just put it all in one function? Or is there a way to call two functions at once?

我应该把它全部放在一个函数中吗?或者有没有办法一次调用两个函数?

回答by Pebbl

You have multiple ways of approaching this, the easiest for your current set up would be:

您有多种方法可以解决这个问题,对于您当前的设置来说,最简单的方法是:

combined function

组合功能

The following will run both functions no matter what state is returned each time, because they are not executed inline as part of a logical expression which will "short circuit" when getting a false value:

无论每次返回什么状态,以下都将运行这两个函数,因为它们不是作为逻辑表达式的一部分内联执行的,逻辑表达式在获得假值时会“短路”:

function validateForm(){
  var validation = true;
  validation &= validateUserName();
  validation &= validatePassword();
  return validation;
}

And then in your form markup:

然后在您的表单标记中:

<form onsubmit="return validateForm()">

If would probably be advisable, in the interests of making more reusable code, to modify your validation functions so that they accept a formargument. This would mean you could do the following:

如果为了制作更多可重用的代码,修改您的验证函数以便它们接受form参数可能是可取的。这意味着您可以执行以下操作:

<form onsubmit="return validateForm(this);">

.. and have your receiving function do the following:

.. 并让您的接收功能执行以下操作:

function validateForm(form){
  var validation = true;
  validation &= validateUserName(form);
  validation &= validatePassword(form);
  return validation;
}

add multiple events

添加多个事件

You could also implement this via the preferred way of applying event listeners which is to use addEventListenerinstead of the html attribute onsubmit:

您还可以通过应用事件侦听器的首选方式来实现这一点,addEventListener而不是使用html 属性onsubmit

/// wait for window load readiness
window.addEventListener('load', function(){
  /// you could improve the way you target your form, this is just a quick eg.
  var form;
  form = document.getElementsByTagName('form')[0];
  form.addEventListener('submit', validateUserName);
  form.addEventListener('submit', validatePassword);
});

The above assumes that it's required to support modern browsers. If you wish to support older versions of internet explorer you'd be better off making a function to apply your event handling e.g:

以上假设需要支持现代浏览器。如果您希望支持旧版本的 Internet Explorer,您最好创建一个函数来应用您的事件处理,例如:

function addEventListener( elm, evname, callback ){
  if ( elm.addEventListener ) {
    elm.addEventListener(evname, callback);
  }
  else if ( elm.attachEvent ) {
    elm.attachEvent('on'+evname, callback);
  }
}

This second option makes it harder to exert a global control over what gets validated, where, when and in what order, so I'd recommend the first option. However I'd would also recommend at least applying your singular submithandler using the JavaScript method above, rather than using onsubmit="".

第二个选项使得对验证的内容、地点、时间和顺序进行全局控制变得更加困难,因此我推荐第一个选项。但是,我也建议至少submit使用上面的 JavaScript 方法应用您的单一处理程序,而不是使用onsubmit="".

回答by Qantas 94 Heavy

Simply combine the two with the logical AND operator:

只需将两者与逻辑 AND 运算符结合起来:

<form name="NewUser" onsubmit="return validateUserName() && validatePassword();" action="">
    <tr>
        <td>Username:</td> 
        <td><input type="text" name="user"/></td> 
    </tr>
    <tr>
        <td class="Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
    </tr>
    <tr>
        <td>Password:</td>
        <td><input type="password" name="pwd"/></td>
    <tr>
        <td class="Information"><em>6-20 characters</em></td>
    </tr>
    <tr>
        <td>Confirm Password:</td>
        <td><input type="password" name="confirmPwd"/></td>
    </tr>
    <tr>
        <td class="Information"><em>just in case you didn't make mistakes!</em></td>
    </tr>
    <input type="submit" value="Submit"/>
</form>

回答by lukeocom

There are a few approaches to this. One is to create a function, such as submitForm() which then calls your two other functions. Perhaps using those function calls as part of ifstatements to provide client side validation.

有几种方法可以解决这个问题。一种是创建一个函数,例如 submitForm() 然后调用其他两个函数。也许使用这些函数调用作为if语句的一部分来提供客户端验证。

The other method is to override the default submit functionality of the form, and instead call the functions as you see fit. jQuery provides an easy approach for this. Have a look at http://api.jquery.com/submit/for more information.

另一种方法是覆盖表单的默认提交功能,并按照您认为合适的方式调用函数。jQuery 为此提供了一种简单的方法。查看http://api.jquery.com/submit/了解更多信息。

Ideally, the validateUser()and validatePassword()functions would be merged into the one function validateUser(). You may want to provide the code of your current functions for advice on how to do that, if you're stuck...

理想情况下,validateUser()validatePassword()函数将合并到 one 函数中validateUser()。如果您遇到困难,您可能希望提供当前函数的代码以获取有关如何执行此操作的建议...

Hope this helps :)

希望这可以帮助 :)

回答by dfsq

Create one function to call all your validators:

创建一个函数来调用所有验证器:

function validate() {
    return validateUserName() && validatePassword();
}

HTML

HTML

<form name="NewUser" onsubmit="return validate()" action="">

Also in your password validation function you refer to incorrect field name.

同样在您的密码验证功能中,您引用了不正确的字段名称。

Fixed code: http://jsfiddle.net/6sB29/

固定代码:http: //jsfiddle.net/6sB29/

If you want to alert all the errors (not only the first) you can try something like this:

如果您想提醒所有错误(不仅是第一个),您可以尝试以下操作:

function validate() {
    var name = validateUserName(),
        pass = validatePassword();   
    return name && pass;
}

http://jsfiddle.net/6sB29/1/

http://jsfiddle.net/6sB29/1/

回答by Ram Singh

Why you are creating two different functions to validate both username and passwords, by the way you can go with this too like below:

为什么要创建两个不同的函数来验证用户名和密码,顺便说一下,您也可以使用以下方法:

Create Another third Function in which these two have to call and check if both returns true then return true otherwise its shows message or whatever you want to do.

创建另一个第三个函数,其中这两个函数必须调用并检查两者是否都返回 true 然后返回 true 否则它会显示消息或您想做的任何事情。

Here is the code by which you can do it:

这是您可以执行的代码:

function validateUserName(NewUser) {
        var u = document.forms["NewUser"]["user"].value
        var uLength = u.length;
        var illegalChars = /\W/; // allow letters, numbers, and underscores
        if (u == null || u == "") {
            alert("You left Username field empty");
            return false;
        }
        else if (uLength < 4 || uLength > 11) {
            alert("The Username must be between 4 and 11 characters");
            return fasle;
        }
        else if (illegalChars.test(u)) {
            alert("The username contains illegal characters");
            return false;
        }
        else {
            return true;
        }
    }

    function validatePassword(pwd, confirmPwd) {
        var p = document.forms["NewUser"]["pwd"].value
        var cP = document.forms["NewUser"]["cP"].value
        var pLength = p.length;
        if (p == null || p == "") {
            alert("You left the password field empty");
            return false;
        }
        else if (pLength < 6 || pLength > 20) {
            alert("Your password must be between 6 and 20 characters in length");
            return false;
        }
        else if (p != cP) {
            alert("Th passwords do not match!");
            return false;
        }
    }



    function finalvalidate() {
        var newuser = $('[id$=newuser]').val();
        var usernameresult = validateUserName(newuser);
        var pwd = $('[id$=pwd]').val();
        var confirmPwd = $('[id$=confirmPwd]').val();
        var pwdresult = validatePassword(pwd, confirmPwd);
        if (usernameresult == true && pwdresult == true) {
            return true;
        } else {
            return false;
        }
    }

Hope this will work for you..

希望这对你有用..

回答by Karan

try this

尝试这个

onsubmit="return fun2() && fun3();"