简体   繁体   English

使用PHP和javascript进行HTML表单验证的简便方法

[英]easy way to do HTML form validation with PHP and javascript

I'm working on a PHP application. 我正在开发一个PHP应用程序。 It consists among others in html forms. 它包含在html表单中。
My question is how to implement form validation in an easy way and without requiring to duplicate validation code both on server (using PHP) and on browser (using Javascript). 我的问题是如何以简单的方式实现表单验证,而无需在服务器(使用PHP)和浏览器(使用Javascript)上复制验证代码。
I've devised a method using ajax. 我已经设计了一个使用ajax的方法。 When an input looses focus (onblur event) it would make an ajax call to the server with the data it contains. 当输入失去焦点(onblur事件)时,它将使用它包含的数据对服务器进行ajax调用。 The response would be an error message if the value is not valid or else an empty string. 如果值无效,则响应将是错误消息,否则为空字符串。 But the code is very bloated on both server and browser and probably very buggy. 但是代码在服务器和浏览器上都非常臃肿,可能非常多。 Could you point me in the right direction? 你能指出我正确的方向吗? Is always input validation that complex or I should be using a different approach? 总是输入验证复杂或我应该使用不同的方法? Many thanks for those who take the time to read my post, and extra tanks to those who answer. 非常感谢那些花时间阅读我的帖子的人,以及那些回答的人的额外坦克。

Input validation is very complex. 输入验证非常复杂。 You need to make sure the input is EXACTLY valid for your datatypes. 您需要确保输入对您的数据类型完全有效。 This will usually include custom validation for every project. 这通常包括每个项目的自定义验证。 There is no substiute for both client side and server side validation. 客户端和服务器端验证都没有替代。

Client side validation provides a snappy ui. 客户端验证提供了一个快速的ui。 Every thing that a user types in can be and should be validated client side so that no request has to be made to the server (reducing latency). 用户键入的每个内容都可以并且应该在客户端验证,以便不必向服务器发出请求(减少延迟)。 This does not mean it is a substitue for server side validation, Because any person can see the request being made through a tool like firebug and submit any data they want to your server. 这并不意味着它是服务器端验证的替代品,因为任何人都可以通过像firebug这样的工具看到请求,并将他们想要的任何数据提交给您的服务器。

Server side you have to make sure data is of the type expected or you can open yourself up to sql injection or many other malicious attacks. 服务器端你必须确保数据是预期的类型,或者你可以自己打开sql注入或许多其他恶意攻击。

This is actually a very good reason to look at any of of the many php mvc frameworks. 这实际上是查看许多php mvc框架中的任何一个的非常好的理由。 Most include form helpers that will significantly reduce the code you have to write for validation. 大多数包括表单助手,这将显着减少您必须编写的代码以进行验证。

You always need server-side validation. 您始终需要服务器端验证。 However, you can make your life easier on the client side by relying on third-party libraries. 但是,依靠第三方库,您可以在客户端使您的生活更轻松。

The easiest way to do basic validation is to use HTML5. 进行基本验证的最简单方法是使用HTML5。 This includes stuff like required field, number ranges and regex checks. 这包括必填字段,数字范围和正则表达式检查等内容。 No third party library required and browsers not capable of HTML5 will just ignore the validation. 不需要第三方库,不支持HTML5的浏览器将忽略验证。 Which is no problem because the input will be validated on the server. 这没有问题,因为输入将在服务器上验证。

Another way would be to use the jQuery validation extension . 另一种方法是使用jQuery验证扩展 With this library you only have to output some classes in your form fields. 使用此库,您只需在表单域中输出一些类。

If your are using the Zend_Form library to generate your forms and do the validation, you may have look at this article: http://codeutopia.net/blog/2008/04/04/client-side-validation-with-zend_form/ 如果您使用Zend_Form库生成表单并进行验证,您可以查看以下文章: http//codeutopia.net/blog/2008/04/04/client-side-validation-with-zend_form/

I strong recommend you Bassistance jQuery Validation plugin . 我强烈推荐你使用Bassistance jQuery Validation插件

Always implement strong server side validation along with this. 始终实施强大的服务器端验证。

I just post the data to a php that verifies everything via ajax. 我只是将数据发布到一个通过ajax验证所有内容的php。 Then I return errors in a json string, each error has the name of the input that failed and an error string. 然后我在json字符串中返回错误,每个错误都有输入失败的名称和错误字符串。 Using jQuery I loop through the json object, and turn the inputs read and list error string. 使用jQuery我循环遍历json对象,并将输入读取并列出错误字符串。 You can have the form submit to this script so that if javascript is turned off the form gets checked the the same php script. 你可以让表单提交给这个脚本,这样如果关闭javascript,表单会被检查相同的php脚本。

function submitForm() {
$.ajax({
  type: 'post',
  url: 'cgi-bin/s_contact.php',
  data: $("#contact").serialize(),
  dataType: 'json',
  success: function(data) {
      if(data.answer == 'true') {
        $("#showErrors").removeClass("progressbar");
         $("#showErrors").html('<h2>Message Has Been Sent!</h2>');
         setTimeout(function() {
             window.location = $("#zsite").val(); 
         },2000);
      }
      else {
          se = $("#showErrors");
          se.removeClass("progressbar");
          se.html('');
          se.append('<ul id="showeror"></ul>');
          $.each(data,function(index,val) {
            $('input[name='+index+']').css('background-color','#ff9');
            $('#showeror').append('<li>'+val+'</li>');
          });
      }
  },
  error: function(msg) {
        alert('Error: '+msg.error); 
  }
});

} }

If you use a good javascript validation plugin you'll find they are quite portable with your server side validation. 如果您使用一个好的javascript验证插件,您会发现它们在您的服务器端验证时非常便携。 I probably need to explain this further so bear with me a little. 我可能需要进一步解释这个,所以请耐心等待一下。 I'll refer to http://rickharrison.github.com/validate.js/ to help me here, but there quite a few others. 我会参考http://rickharrison.github.com/validate.js/来帮助我,但还有很多其他人。

Personally, I use the Symfony form framework for validation but you can use other frameworks or have a go at your own. 就个人而言,我使用Symfony表单框架进行验证,但您可以使用其他框架或自己动手。 The important thing is that you only define a set of validation rules once which can in-turn be used to drive the client-side validation. 重要的是,您只需定义一组验证规则 ,然后可以使用这些验证规则来驱动客户端验证。

This way you won't have any inconsistencies between the two separate validation processes, ensuring your application is DRY. 这样,两个单独的验证过程之间就不会有任何不一致,从而确保您的应用程序是干的。 Also, your the client-side validation can be loaded with the page since these rules have been pre-defined in your server-side code and you won't need all those ajax requests. 此外,您可以使用页面加载客户端验证,因为这些规则已在服务器端代码中预先定义,您不需要所有这些ajax请求。

If you're not familiar with any PHP form frameworks or what I mean by defining your validation rules I can make things a bit clearer. 如果您不熟悉任何PHP表单框架或我通过定义验证规则的意思,我可以使事情更清楚一些。

The below array could be used to loop over two $_POST fields, email and number, on the server-side. 以下数组可用于在服务器端循环两个$ _POST字段,电子邮件和号码。 This information can also be easily passed to a client-side validator (eg json_encode($validators)). 此信息也可以轻松传递给客户端验证器(例如json_encode($ validators))。 You might need to rework things a little, depending on what format the client-side expects its rules. 您可能需要稍微重做一些事情,具体取决于客户端期望其规则的格式。 But more importantly your validation logic is stored in one place. 但更重要的是,您的验证逻辑存储在一个地方。

$validators = array(
   'email' => array(
       'rules' => array(
           'blank' => false,
           'invalid' => '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i',
       ),
       'messages' => array(
           'blank' => 'Missing email',
           'invalid' => 'Invalid email',
       ),
    ),
    'number' => array(
       'rules' => array(
           'blank' => false,
           'invalid' => '/\d/',
       ),
       'messages' => array(
           'blank' => 'Missing number',
           'invalid' => 'Not a number'
       ),
     ......

总是使用服务器端脚本来检查输入,因为如果你使用客户端(javascript)那么任何人都可以通过使用各种技术,如禁用JavaScript等使你傻瓜。

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

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