简体   繁体   English

通过 jQuery 和 PHP 验证表单输入字段

[英]Form input fields validation via jQuery and PHP

I want to validate my form input fields on button click in jQuery.我想在 jQuery 中单击按钮时验证我的表单输入字段。 But I don't want to use client side validation.但我不想使用客户端验证。 How can I add PHP server-side validation on button click?如何在按钮单击时添加 PHP 服务器端验证?

I am using modal box for form.我正在使用模态框作为表单。

I know it is a beginner's level question, but currently I am unable to figure it out because of my low expertise.我知道这是一个初学者级别的问题,但由于我的专业知识低,目前我无法弄清楚。

Yes you can validate using PHP and it's not a big deal.是的,您可以使用PHP进行验证,这没什么大不了的。 I'll provide a simple example here to pass the form data to PHP for validation.我将在此处提供一个简单的示例,将表单数据传递给 PHP 进行验证。

<?php
if( isset($_POST['submitForm']) )
{
    $userName = $_POST['userName'];
    $userAge = $_POST['userAge'];
    
    if ($userAge > 21)
    {
      echo "Hey " + userName;
    }
}
?>
<html>
<body>
<form method="POST" action=""> 
    Name: <input type="text" name="userName">
    Age: <input type="number" name="userAge">
    <input type="submit" name="submitForm" value="Validate"> 
</form>
</body>
</html> 

If you wish to pass the data to another page to validate, just give the file name in action attribute, like action="Your_PHP_File.php" and validate separately.如果您希望将数据传递到另一个页面进行验证,只需在action属性中提供文件名,如action="Your_PHP_File.php"并单独验证。 Just a tip : If you wish to redirect on success (heavily used):只是一个提示:如果您希望成功重定向(大量使用):

header("Location: Your_URL_Here");

Anyways, this is not a better user experience.无论如何,这不是更好的用户体验。 You must use client side validation using JavaScript/any JavaScript framework, and use language like PHP only to communicate with the server, such as storing the data in the database, retrieving data from the database.您必须使用 JavaScript/任何 JavaScript 框架进行客户端验证,并且仅使用 PHP 等语言与服务器通信,例如将数据存储在数据库中,从数据库中检索数据。

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

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