简体   繁体   English

高效有效的表单验证

[英]Efficient and effective form validation

I have a working example of a form here .在这里有一个表单的工作示例。 I need to use Javascript of Jquery form validation to verify that the user has inputted his/her own data.我需要使用 Javascript of Jquery 表单验证来验证用户是否输入了他/她自己的数据。 So far I have tried to check for values, but obviously this didn't work, because the inputs and textarea already have a default value, and so the user can submit straight away without filling in anything.到目前为止,我已经尝试检查值,但显然这没有用,因为输入和文本区域已经有一个默认值,因此用户可以直接提交而无需填写任何内容。

Any help would be much appreciated.任何帮助将非常感激。

Thanks in advance!提前致谢!

EDIT编辑

I am using this php to send the submitted data to an email address:我正在使用这个 php 将提交的数据发送到 email 地址:

<?php
$name = $_POST['name'];
if ($name=="") {
$name="Nothing was returned for this part of the form.";
}
$email = $_POST['email'];
if ($email=="") {
$email="Nothing was returned for this part of the form.";
}
$subject = $_POST['subject'];
if ($subject=="") {
$subject="Nothing was returned for this part of the form.";
}
$comments = $_POST['comments'];
if ($comments=="") {
$comments="Nothing was returned for this part of the form.";
}
$theMessage7="<b>Results from the form at www.site.co.uk/contact.html</b><br /><br />" . "Name:&nbsp;" . $name . "<br />" . "Email:&nbsp;" . $email . "<br />" . "Subject:&nbsp;" . $subject . "<br />" . "Message:&nbsp;" . $comments . "<br />";
$theEmail7="mail@mail.com";
$theSubject7="New form submission";
$theHeaders7="MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1
From: form@bikeinc.co.uk
Subject: New form submission";
$theErrorFile7="www.site.co.uk/12345";
$theThanxFile7="received.html";
if (!(mail($theEmail7, stripslashes($theSubject7), stripslashes($theMessage7), stripslashes($theHeaders7)))) {
    header ( "Location: $theErrorFile7" );
        }else{
    header ( "Location: $theThanxFile7" );
}
?>

The effective form of form validation on user side is to use jQuery validation plugin , see examples on proper usage. 用户端表单验证的有效形式是使用jQuery验证插件 ,请参见有关正确用法的示例。

Note: user ALWAYS can disable javascript or use some kind of bot to send invalid not checked data, so you always have to write proper server side validation. 注意:用户始终可以禁用javascript或使用某种漫游器来发送无效的未经检查的数据,因此您始终必须编写适当的服务器端验证。

Frameworks often provides effective way of form validation, such as Zend_Validator . 框架通常提供有效的表单验证方式,例如Zend_Validator

It's common to prepare method for your php application such as: 为您的php应用程序准备方法是很常见的,例如:

public function validate() {
  if( !isset( $_POST['name'])){
    $this->field = 'name';
    $this->msg = 'Invalid user name';
    return false;
  }

  ...
  return true;
}

And use it in both sending script: 并在两个发送脚本中使用它:

if( $form->validate()){
  send();
}

And in check script: 并在检查脚本中:

$data = array();
if( $form->validate()){
  $data['status'] = 'ok';
} else {
  $data['status'] = 'failure';
  $data['field'] = $form->field;
  $data['msg'] = $form->msg;
}
echo json_encode( $data);

End than use jquery and javascript for form validation "on the fly": 最终不如使用jquery和javascript进行“即时”表单验证:

<input type="text" name="name" value="" onchange="ajaxValidate();" />

function ajaxValidate(){
  // Call ajax to check script and put results
}

If you're just building small project with one form or so, you could implement few methods like: 如果您仅使用一种形式构建小型项目,则可以实现以下几种方法:

function is_post( $key); // Shorter than write isset( $_POST[ $key])
function get_post( $key, $defaultValue); // Shorter than isset( $_POST[ $key]) ? $_POST[ $key] : $default
function is_email(...); 
...

And jQuery validation: 和jQuery验证:

function validateForm() {
  $('.input').removeClass( 'error');
  var status = true;
  if( $('input[name=name]').val() == '')){
     $('input[name=name]').addClass( 'error');
     setMessage( 'Name cannot be empty');
     status = false;
  }

  ...

  return status;
}

<form onsubmit='return validateForm();' ...>

Form validation is the process of ensuring that user input is complete, accurate, and reasonable before it is accepted and stored.表单验证是在接受和存储用户输入之前确保用户输入完整、准确和合理的过程。 It is an important aspect of web development as it helps to prevent the submission of invalid or malicious data.这是 web 开发的一个重要方面,因为它有助于防止提交无效或恶意数据。 There are several ways to achieve efficient and effective form validation:有几种方法可以实现高效有效的表单验证:

Use client-side validation: This type of validation is performed on the client's device (eg, web browser) using JavaScript. It is fast and can provide immediate feedback to the user, but it can be bypassed if the user has disabled JavaScript or is using a browser that does not support it.使用客户端验证:这种类型的验证是在客户端设备(例如,web 浏览器)上使用 JavaScript 执行的。它速度很快,可以向用户提供即时反馈,但如果用户已禁用 JavaScript 或正在使用,则可以绕过它使用不支持它的浏览器。

Use server-side validation: This type of validation is performed on the server after the form has been submitted.使用服务器端验证:这种类型的验证在提交表单后在服务器上执行。 It is more reliable than client-side validation because it cannot be bypassed, but it can cause delays as the form must be submitted and the server must process it before the user can receive feedback.它比客户端验证更可靠,因为它无法绕过,但它可能会导致延迟,因为必须提交表单并且服务器必须在用户收到反馈之前对其进行处理。

Use both client-side and server-side validation: Combining both types of validation can provide the best of both worlds.同时使用客户端和服务器端验证:结合两种类型的验证可以提供两全其美的效果。 Client-side validation can provide immediate feedback to the user and reduce the load on the server, while server-side validation can ensure that the data is valid and secure.客户端验证可以向用户提供即时反馈并减少服务器的负载,而服务器端验证可以确保数据有效和安全。

Use regular expressions to validate input: Regular expressions are a powerful tool for validating input and can be used to check that a string matches a specific pattern (eg, an email address, a phone number).使用正则表达式验证输入:正则表达式是验证输入的强大工具,可用于检查字符串是否匹配特定模式(例如,email 地址、电话号码)。

Use pre-built form validation libraries: There are many pre-built libraries and frameworks (eg, jQuery Validation Plugin, AngularJS) that can make it easy to implement form validation with minimal effort.使用预建的表单验证库:有许多预建的库和框架(例如,jQuery Validation Plugin,AngularJS)可以轻松地以最小的努力实现表单验证。

Use appropriate input types and attributes: HTML5 introduced several new input types (eg, email, url, number) and attributes (eg, required, min, max) that can be used to improve the accuracy of form validation.使用适当的输入类型和属性:HTML5 引入了几种新的输入类型(例如,email、url、数字)和属性(例如,required、min、max),可用于提高表单验证的准确性。

You could try using the HTML5 required attribute... however this will only work with browsers that support it. 您可以尝试使用HTML5必需属性...但是,这仅适用于支持该属性的浏览器。 For example: 例如:

<label for="name">Name:</label>
<input type="text" name="name" required="required" id="name">

This will only work if you use the HTML5 doctype though. 但是,仅当您使用HTML5文档类型时,这才起作用。

Then for the PHP validation in the instance the HTML5 validation hasn't run due to incompatible browser... or if JavaScript doesn't run due to it being disabled/unavailable/broken. 然后,对于实例中的PHP验证,由于浏览器不兼容而导致HTML5验证未运行...或者由于禁用/不可用/损坏而导致JavaScript无法运行。

// check input
if (empty($_POST['name']))
{
    $errors['name'] = 'Please provide your name.';
}

I then display the errors when I show the page to the user after the authentication has gone through. 验证通过后向用户显示页面时,我将显示错误。

<label for="name">Name:</label>
<input type="text" name="name" required="required" id="name">
<?php if (!empty($errors['name'])): ?><p class="error"><?php echo $errors['name']; ?></p><?php endif; ?>

Also... remember to protect yourself from SQL injection, XSS and mallicious code injection if this is going to be saved in a database or displayed to other users. 另外...记住要保护自己免受SQL注入,XSS和恶意代码注入的侵害,如果这要保存在数据库中或显示给其他用户。

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

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