简体   繁体   English

尝试验证表单客户端和服务器端

[英]Trying to validate a form client and server side

The client side validation looks something like this: 客户端验证看起来像这样:

function validateFname() {
    var x = document.getElementById('fname').value; 
    if (x==null || x=="")
    {
    alert("First name must be filled out");
    return false;
    }
}

The server side below it: 它下面的服务器端:

if(isset($_POST['SubmitForm'])){
if(empty($_POST['fname'])){
    echo "First name cannot be empty!<br/><br/>";
    return false;
}

and the form itself below that: 以及下面的表格:

<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>"
accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" onsubmit="return validateFname()"
class="required" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" value="Send"/>

Ofcourse there is a lot more to it but ive just given one example above. 当然,它还有很多其他功能,但上面仅举了一个例子。 I am trying to figure out why the (clientside)javascript function is not working and instead the (server) php error is coming up. 我试图弄清楚为什么(clientside)javascript函数无法正常工作,而出现(server)php错误。 I need to be able to have the client run validation checks before the server to reduce load. 我需要能够让客户端在服务器之前运行验证检查以减少负载。

The onsubmit is a event that belongs to the <form> element. onsubmit是属于<form>元素的事件。 You have placed it with the submit button which won't work. 您已将其放置在“提交”按钮上,该按钮将不起作用。

Here's a working fiddle: 这是一个工作的小提琴:

Demo 演示

Reference 参考

<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>" accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname"  value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" onClick="return validateFname()"  value="Send"/>
</form>

try the above code. 试试上面的代码。 Instead of using onSubmit in input text field use onClick in submit button. 不用在输入文本字段中使用onSubmit,而是在提交按钮中使用onClick。 good luck 祝好运

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

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