具有常见JS验证的多个表单

时间:2015-10-22 01:26:49

标签: javascript jquery html forms validation

我是Javascript和jQuery的新手。我得到的只是这个JS函数来验证我的表单。我在这两种形式中都有一些共同的领域。我没有调用不同的函数来验证不同的形式,而是想要一个JS函数来验证两个表单中的所有公共字段。仅供参考这两种表格都在不同的页面中。

JS

function check1(){
    var x = document.forms["form1"]["type"].value;
    if (x == null || x == "") {
        alert("Please Enter Type");
        return false;
    }

function check2(){
    var x = document.forms["form2"]["type"].value;
    if (x == null || x == "") {
        alert("Please Enter Type");
        return false;
    }

HTML

Form1中

<form name="form1" method="post" action="#" onsubmit="return check1()">
<input type="text" name="type" id="type">
</form>

窗口2

<form name="form2" method="post" action="#" onsubmit="return check2()">
<inout type="text" name="type" id="type">
</form>

先谢谢。请耐我,我是新手。

1 个答案:

答案 0 :(得分:1)

以下是两种形式的常见功能: (即代替check1和check2,使用检查)。

function check(){
    var frm = document.forms["form1"] || document.forms["form2"];
    var x = frm["type"].value;
    if (x == null || x == "") {
        alert("Please Enter Type");
        return false;
    }
    return false;
}