Javascript 提交前验证表单(比检查空字段更复杂)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3206166/
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-23 03:40:41  来源:igfitidea点击:

validate form before submitting (more complicated than checking for empty fields)

phpjavascriptformsvalidation

提问by vee

i have a form containing inputs for times (specifically, an opening and closing time). when the submit button is pressed, it goes to a php page where these inputs are added to a database. i want to check a few things before allowing the form to submit. for example, i want to make sure that the start time is earlier than (less than) the end time. here's the form:

我有一个包含时间输入的表单(特别是开始和关闭时间)。当提交按钮被按下时,它会进入一个 php 页面,在那里这些输入被添加到数据库中。我想在允许表单提交之前检查一些事情。例如,我想确保开始时间早于(小于)结束时间。这是表格:

            Opens:
            <select name="starthour1">
                <option value="00">12</option>
                <option value="01">1</option>
                <option value="02">2</option>
                <option value="03">3</option>
                <option value="04">4</option>
                <option value="05">5</option>
                <option value="06">6</option>
                <option value="07">7</option>
                <option value="08">8</option>
                <option value="09">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
            </select> : 
            <select name="startminute1">
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
                <option value="59">59</option>
            </select> 
            <select name="startwhen1">
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>

            Closes:
            <select name="endhour1">
                <option value="00">12</option>
                <option value="01">1</option>
                <option value="02">2</option>
                <option value="03">3</option>
                <option value="04">4</option>
                <option value="05">5</option>
                <option value="06">6</option>
                <option value="07">7</option>
                <option value="08">8</option>
                <option value="09">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
            </select> : 
            <select name="endminute1">
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
                <option value="59">59</option>
            </select> 
            <select name="endwhen1">
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>

i found javascript code for how to check individual form elements, but i can't figure out how i could combine multiple without submitting. in my php page, i have the following code:

我找到了用于检查单个表单元素的 javascript 代码,但我不知道如何在不提交的情况下组合多个元素。在我的 php 页面中,我有以下代码:

$starthour1=$_POST['starthour1'];
$startminute1=$_POST['startminute1'];
$startwhen1=$_POST['startwhen1'];
$endhour1=$_POST['endhour1'];
$endminute1=$_POST['endminute1'];
$endwhen1=$_POST['endwhen1'];

$start_time1=$end_time1="";

    if($startwhen1=="pm"){
        $starthour1=$starthour1+12;
    }
    if($endwhen1=="pm"){
        $endhour1=$endhour1+12;
    }
    $start_time1=$starthour1.":".$startminute1.":00";
    $end_time1=$endhour1.":".$endminute1.":00";
    if($end_time1=="00:00:00"){
        $end_time1="23:59:00";
    }

echo "<br>start time is ".$start_time1;
echo "<br>end time is ".$end_time1;

$startnum=str_replace(":", "", $start_time1);
$endnum=str_replace(":", "", $end_time1);
if($endnum<$startnum){
    echo "<br>start time can't be later than end time!";
}
else{
   //add to database
}

however, checking this stuff after submitting doesn't make sense. i suppose i could redirect back to the initial page if the error was found, but that doesn't seem efficient.

但是,提交后检查这些东西没有意义。我想如果发现错误,我可以重定向回初始页面,但这似乎效率不高。

also, i was thinking maybe i could have some php on the page with the form that checks for validity. if it validates, it then posts to the php page that inserts stuff into the database. does this make sense and is it possible?

另外,我在想也许我可以在页面上使用一些 php 来检查有效性。如果它通过验证,则它会发布到将内容插入数据库的 php 页面。这有意义吗?有可能吗?

is there a better solution? i imagine there is something i could do with javascript but i haven't been able to figure it out.

有更好的解决方案吗?我想我可以用 javascript 做一些事情,但我一直无法弄清楚。

additionally i'd like to inform the user of invalid inputs with text that appears next to the input box. i should be able to figure this out once the rest is working though.

另外,我想通过输入框旁边显示的文本通知用户无效输入。一旦其余部分工作,我应该能够弄清楚这一点。

thanks.

谢谢。

回答by amfeng

Have the onSubmit() or action of the form call a JavaScript function, like this:

让表单的 onSubmit() 或 action 调用 JavaScript 函数,如下所示:

<form id="form" onSubmit="return doSubmit();" action="#">

Then, in doSubmit() you can actually perform any of the validations (and only actuallysubmit the form if they pass)

然后,在 doSubmit() 中,您实际上可以执行任何验证(并且只有在通过时才实际提交表单)

function doSubmit(){       
    if (validationsPass()) {
         $('#form').submit();
    }
}

To inform users of invalid input next to the actual form field, you can have hidden divs or spans next to each field, and use Javascript to un-hide them if they fail some sort of validation.

要通知用户实际表单字段旁边的无效输入,您可以在每个字段旁边隐藏 div 或跨度,如果它们未通过某种验证,则使用 Javascript 取消隐藏它们。

if(!fieldNotValid){
     $('#field-error').show(); //Or use effects like .highlight()
}

回答by Elzo Valugi

Always check at PHP level the user input, no matter if you check it in the client side as well using javascript.

始终在 PHP 级别检查用户输入,无论您是否在客户端也使用 javascript 进行检查。

In javaScript I recommend you to use a Js library like jQuery that has a pluginfor form validation. Very useful and easy to implement.

在 javaScript 中,我建议您使用像 jQuery 这样的 Js 库,它有一个用于表单验证的插件。非常有用且易于实施。

At PHP level I recommend you to use filter_varfunctions. Very efficient as well.

在 PHP 级别,我建议您使用filter_var函数。效率也很高。

回答by Gordon

Consider turning the Form Data into DateTimeobjects instead. This will make comparison much easier than fiddling with each part individually. It will also make sure the DateTime string put into the database is safe for insertion, because you will get the string from the format()method.

考虑将表单数据转换为DateTime对象。这将使比较比单独摆弄每个部分要容易得多。它还将确保放入数据库的 DateTime 字符串可以安全插入,因为您将从format()方法中获取字符串。

回答by vee

thanks for the help! i ended up using:

谢谢您的帮助!我最终使用了:

<form action="add.php" onsubmit="return validate_form()" method="POST" name="addform">

with:

和:

function validate_form(){
        var f = document.addform;
        var start, end, starthour, endhour;
        var valid=true;
        ..........

            starthour=f.starthour1.value;
            endhour=f.endhour1.value;
            if(f.startwhen1.value=="pm"){
                var starthournum = starthour * 1;
                starthournum = starthournum+12;
                starthour = starthournum.toString();
            }
            if(f.endwhen1.value=="pm"){
                var endhournum = endhour * 1;
                starthournum = starthournum+12;
                starthour = starthournum.toString();
            }
            start = starthour+f.startminute1.value;
            end = endhour+f.endminute1.value;

            if(end=="0000"){
                end="2359";
            }

        if(end<start){
            alert("Start time can't be later than end time!");
            valid=false;
        }

        return valid;
}