Validate Form with PHP AND JavaScript?

前端 未结 4 2071
夕颜
夕颜 2021-01-07 05:13

Is it possible to validate a form with PHP and JavaScript? I\'m currently able to do both using my existing form, but only on

4条回答
  •  终归单人心
    2021-01-07 05:25

    UPDATED in responce to comments

    First of all, javascript can't be a secure validator, for obvious reasons! it can be a fancy way of displaying alerts and notice but is just sugar!

    Real validation must be done in PHP or other server-side language as well as on Database side by checking and formatting values!

    This simple script is just a demostration of how you can built a smart validator, but of course is just a proof of concept!


    DEMO: http://jsbin.com/aceze/29

    $(function() {
        $('#myform').submit(function() {
            var error = false; // flag
    
            $('.email,.digits,.empty,.some').each(function() {
    
                var check = this.className;
    
                if (check == 'empty') if (!checkEmpty(this.value)) error = true;
    
                if (check == 'digits') if (!checkDigits(this.value)) error = true;
    
                if (check == 'email') if (!checkEmail(this.value)) error = true;
    
                if (check == 'some') if (!checkSome(this.value)) error = true;
    
                if (error) {
                    $(this).css('border', '1px solid red');
                } else {
                    $(this).css('border', '1px solid green');
                }
            });
    
            if (error) {
                return false;
            }
        });
    });
    

    Then regarding the

    action, you don't need to have the path of the php page in it, but you must use AJAX for make the POST OR just leave the review.php where is see theese snippets below:

      // FIRST SNIPPET action="#"
               if ( error == false ) {
               //if all is ok give our form it's php
               $(this).attr('action','review.php');
               } else {
               // error  
               // place false here so the form don't submit if validation fail!
               return false;
             }
    
      // SECOND SNIPPET action="review.php"
    
              if ( error == true ) {
            // form submit only if validation pass
               return false;
               } 
    
      // THIRD SNIPPET action="#" AJAX
    
        if ( error == false ) {
               // success
               } else {
               // error  
    
             }
         // this false prevent the form submit in anycase, cause we use AJAX
         return false;
    

提交回复
热议问题