1

I'm trying to validate the fields in a form using PHP, but I need something similar to e.preventDefault() to stop the page from refreshing/loading if there are errors in the validation. I'm not very familiar with JavaScript/jQuery, so I'd prefer to handle all of the POST data with PHP (if possible). I was trying to run the checkForm() function on submit, but I realized it was always returning true since it runs before the data gets posted. I also thought about creating a JS function to call e.preventDefault(), but I think my only option would be a (#form).submit() function and I want to avoid having to retrieve and post data in JS/jQuery because some elements are DOM elements and I'm not sure how to access them in JS/jQuery.

To give you an idea of the DOM elements I'm working with, here's a jsfiddle that creates rows dynamically:

https://jsfiddle.net/hnj6ed1y/52/

There could be multiple rows and the fields have similar names (ie: textfield1, textfield2, etc.).

Any ideas? Thank you in advance for all of your help!

    <?php

    // setting initial variables here

    ?>

    <script>

    var isDateTimeValid = true;

    function checkDates(val) {

        if (val == false) {
            isDateTimeValid = false;
        }
        else {
            isDateTimeValid = true;
        }
    }


    function checkForm () {

        if (isDateTimeValid == true) {
            return true;
        }
        else {
            alert("Please check date/times");
            return false;
        }
    }
    </script>

    <?php

    if(isset($_POST['next'])){

        // Validating POST data here

        $dateValid = convertOORDateTime($date1, $time1, $date2, $time2);

        if ($dateValid < 1) {
            echo "<script> checkDates(false); </script>";
            $errors[] = 'Please make sure your dates are correct';
        }
        else {
            echo "<script> checkDates(true); </script>";
        }

    }

    $err_msg = '';

    if(!empty($errors)){

        // want to stop page refresh/load here

        $err_msg = '<p class="error">'.implode('<br />', $errors).'</p>';   
    }

    ?>

    <!DOCTYPE html>
    <form name="form1" id="form1" method="post" action="<?php print $thispage;?>" onsubmit="return checkForm()">

        <?php echo $err_msg; ?>

    </form>
R. Kelly
  • 93
  • 2
  • 9
  • Either you are confused or I am. – bassxzero Dec 02 '15 at 00:44
  • @bassxzero I am definitely confused. I'm just attempting to validate the POST data in PHP (which is working), but I need to prevent the page from reloading when I come across invalid data. I know the "echo" in the HTML requires the page to be reloaded, but I can work around that. – R. Kelly Dec 02 '15 at 00:46
  • So you want the server to check your page without refreshing the page? Is that possible? – Adam Buchanan Smith Dec 02 '15 at 00:50
  • I don't think your code is structured to do what you want. If you are going to rely on javascript and you want to validate the data server side, I would prevent the default submit action, use Ajax to submit the form data to a processing validation script, then submit the form if the data was valid. – bassxzero Dec 02 '15 at 00:51
  • @bassxzero I've never used Ajax, but would that mean I use (#form).submit, call e.preventDefault on that listener, and use Ajax within that function? Any possible pseudo code or example of calling a validation script via Ajax? – R. Kelly Dec 02 '15 at 00:54
  • http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form – bassxzero Dec 02 '15 at 00:55
  • That doesn't solve your error message problem though – bassxzero Dec 02 '15 at 00:55
  • @bassxzero You're right. I like the idea of using Ajax (and seems simple enough), but I won't be able to display error messages to the user, right? – R. Kelly Dec 02 '15 at 01:03
  • right. Why do you not want to refresh? – bassxzero Dec 02 '15 at 01:04
  • @bassxzero I'm trying my best to prevent the table from being cleared. – R. Kelly Dec 02 '15 at 01:12
  • regardless if you use js or jquery the final end all must be php server side validation. Any user can open browser tools and edit your page forms, js etc and then submit. Do not rely on client side validation. Please review my updated answer. – Brian Dec 02 '15 at 02:05

2 Answers2

2

It's weird when your checkForm can't prevent the form submission. Your JS code may throw error and then the code is continued to run.

The easy way is changing the submit button to normal button. Form will not automatically submit when you click normal button. Once the validation is okay, you could manually submit the form by jquery.

$('#button-id').click(function(){
    var valid = true;
    // perform the validation here, for example
    if($('something').val() == "") {
        valid = false;
        // notice user the error
    }
    // Continue to validate

    // Finally, check the valid
    if(valid) {
        ('#form-id').submit();
    }
});

In the validation part, you could probably use jQuery validation, then you could do as followed

var form = $( "#myform" );
form.validate();
$( "button" ).click(function() {
   if(form.valid()) {
       form.submit();
   }
});
  • Will I have to move my validation to JS/jQuery .submit(); function instead of in the PHP code? – R. Kelly Dec 02 '15 at 01:21
  • In your first example, would I need to hardcode the field name in order to validate it (ie: `if($('field1').val() == "")`)? The reason I ask is because I need to compare date fields (ie: `if($('date1').val() > $('date2').val())`, but the user can add as many date fields as they want, so how would I know if there is a date3 and date4 that was added in order to compare them? – R. Kelly Dec 02 '15 at 02:21
  • Probably you will need to use $('input[name^=”value”]') to query input that has name starts with 'value' and find the last one (for example $('input[name^=”value”]:last') or $('input[name^=”value”]').last()). Once you have the number of last one, for example, 7 (hint, you could store number of input by extra attribute like data-id="number-id", this way, you don't need to parse number-id from the name of input), you could use a while loop to compare each with prior one, $('input[name=”value'+i+'”]').val() < $('input[name=”value'+i-1+'”]').val(). – Khanh Truong Dec 02 '15 at 03:24
  • Thanks @Khanh! I will try to create a jsFiddle for this and see if I can get it working. – R. Kelly Dec 02 '15 at 07:01
0

You should keep your validation checks client/server separate. Use JS prior to submit and PHP after. Don't intertwine the two. When you call JS through php the server has to send a response to the browser (client) for anything to happen, thus reloading the page.

Example: echo "<script> checkDates(false); </script>"; Echo() sends output to the browser (client). Which in this instance requires JS to run a function.

Use on.(Blur) to do simple validation in real time prior to submit. Once submitted then you use PHP server side validation. Never rely on the client. JS can be turned off, edited etc via the browser.

<form>
  <input tabindex="1" id="field1" type="text" name="field1" value="value 1" required />
  <input tabindex="2" id="field2" type="text" name="field2" value="value 2" required />
  <input tabindex="3" type="text" name="field3" value="value 3" />
  <input tabindex="4" type="submit" name="submit" value="Submit" />
</form>

<script>
/* Simplistic validation */
jQuery(document).ready(function($){
  jQuery(document).on("blur", "#field1", function(){
    // validate this field

  });

  jQuery(document).on("blur", "#field2", function(){
    // validate this field

  });

});
</script>
Brian
  • 1,025
  • 7
  • 13
  • I am using blur, but some fields need to be compared to other fields (ie: two date fields), so I don't think blur would work in this instance? – R. Kelly Dec 02 '15 at 00:51
  • Blur is not going to help him deal with submitting form data – bassxzero Dec 02 '15 at 00:52
  • Thanks for the clarification, @Brian. I want to avoid the page reloading because it will clear the form if I validate using PHP, but I think I will just have to store their data in a session to recall it after the page reloads. – R. Kelly Dec 02 '15 at 02:25
  • In your original post please describe the overall scope of what you're trying to accomplish. I honestly believe your approach is flawed. No disrespect intended. From what I see you are dynamically generating additional fields, and then wanting to validate them with JS, then on submit validate with Php. Also from inspecting the fiddle source each new field is "temp"+ incremented number. Personally I would use an array approach .... name="field[]" and then js validate the last entry in the array. But that's just me. – Brian Dec 02 '15 at 02:43
  • If you do go the array path you can then on submit repopulate/create the fields with a foreach($field as $value) loop if there are errors. – Brian Dec 02 '15 at 03:12
  • I appreciate the help @Brian. Initially, I was validating with JS because it allowed me to use the alert function and would prevent the form from clearing if the checkForm() function returned false. It was working well until I had to compare fields and my unfamiliarity with JS brought me here, so I thought I'd ask if there was a way to utilize the e.preventDefault() function (or something similar) in PHP that way I can validate without reloading the page if there was an error. I'm glad you guys pointed out how flawed the approach was as I would've never realized it. – R. Kelly Dec 02 '15 at 06:56