1

This is my first post to Stack - I'm fairly new to coding...

I am having a problem with return false for form validation in Safari. return false is working just fine with Chrome and Firefox, but when the incomplete form is submitted in Safari, the alerts fire but the form submission continues anyway. Here's the relevant code, pretty basic stuff...

if (dateField == null || dateField == "" || timeField == null || timeField == ""){

        if (dateField == null || dateField == ""){
            alert("Please select a date");
            }

        if (timeField == null || timeField == ""){
            alert("Please select a time");
            }

            return false;
        };

I've seen similar questions around, but nothing quite solves my problem. Anyway, I know this is probably a pretty amateur issue, but I'd greatly appreciate your help. Thanks!

skwidbreth
  • 7,888
  • 11
  • 58
  • 105
  • 1
    Show your HTML too. The JS looks OK – Dave Aug 13 '15 at 18:05
  • 1
    How exactly is the form sent? You could bind an event listener: `yourForm.addEventListener('submit',function(e){…})` and in that function use `e.preventDefault();` if the fields are empty. Also, please use `===` when comparing to the empty string or to `null` to avoid type coercion. – Sebastian Simon Aug 13 '15 at 18:06
  • What triggers the JS to run? The JS looks appropriate so the answer will lie in your trigger/html. – stubsthewizard Aug 13 '15 at 18:07
  • 1
    Nitpick: If you are using text inputs, not sure how it would be null when you read the string. You need to show more code...how is the validation being called? – epascarello Aug 13 '15 at 18:08
  • @epascarello I assume, OP added this later, because he wanted to try out if at least the comparison against `null` works. – Sebastian Simon Aug 13 '15 at 18:12
  • Thanks everyone - the problem was that I was using an in-line event handler... that said, thanks for the other tips - your expertise is much appreciated. – skwidbreth Aug 13 '15 at 21:21

2 Answers2

1

I assume you are binding a function to the click event on a button (or something) and validate your form then.

Different browsers have different implementations about this. For example, some browsers will take the return value of the function bound to the element (in which case, return false, would be enough to stop the default behaviour of the button). Others do not.

To make sure it works they way you intended, you have to use the preventDefaultfunction.

In this example, the function is the function you bound to the click event of the element. You will have to pass the event to it though (in this case called e.

function(e) {
  e.preventDefault();

  // Your code
  if (dateField == null || dateField == "" || timeField == null || timeField == ""){

    if (dateField == null || dateField == ""){
      alert("Please select a date");
    }

    if (timeField == null || timeField == ""){
      alert("Please select a time");
    }

    // Just like you did correctly, return false
    return false;
  }
}

Depending on what you want, you'll have to move the preventDefault() down to just above your return false; (which I assume in your case you'll want to do, if you want the normal action to happen if your validation is successful).

Wout De Rooms
  • 647
  • 4
  • 10
  • Thank you so much for your thoughtful response - the problem was a silly mistake on my part - using an in-line event handler... lesson learned! However, I really appreciate your calling my attention to the importance of the preventDefault function. – skwidbreth Aug 13 '15 at 21:23
1

To prevent the form from sending, just use Event.preventDefault:

I’m not sure what your HTML looks like, exactly, but I’m sure you can adapt the lines with document.getElementById and make sure that your form has a method and action attribute and no inline event handlers (i.e. onsubmit="…") are used.

// Assuming the DOM is loaded at this point.

var yourForm=document.getElementById('yourForm');

yourForm.addEventListener('submit',function(e){
  "use strict";
  /* If you want to use variables,
     make sure to update their value before checking. */
  var dateField=document.getElementById('dateField').value,
    timeField=document.getElementById('timeField').value;

  if(!dateField || !timeField){ // Validation
    // Message
    if(!dateField){
      alert("Please select a date.");
    }
    else if(!timeField){
      alert("Please select a time.");
    }

    // Prevent the form from sending
    if(e.preventDefault){
      e.preventDefault();
    }
    else if(e.returnValue){
      e.returnValue=false; // For IE8
    }
    return false; // Just to be safe
  }
});
<!-- Here’s a potential HTML structure: -->
<form id="yourForm" action="somewhere.php" method="GET">
  <input id="dateField" type="text"/>
  <input id="timeField" type="text"/>
  <input type="submit"/>
</form>

Setting e.returnValue is just a way that is compatible with Internet Explorer 8, as pointed out in this SO question. If you want to be fully compatible to these older browsers, you’ll need a compatible version of addEventListener as well. You can use jQuery for that. And you don’t need to remove return false;, either.

Also, please be careful when validating your inputs. When comparing against the empty string, use === or !== to avoid type coercion. If you’re sure that the input elements always exist, a simple !field.value should be sufficient. I recommend validating your code with JSHint.

The above code should cover canceling the submission in most more or less modern browsers. If you still have issues, you can do a workaround and disable the submit button or remove the method attribute or something like that if the fields are not valid.

Community
  • 1
  • 1
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • Great, thank you so much for that thoughtful response... you got it - the problem was that I was using an in-line event handler... rookie mistake, I'm a bit embarrassed. I appreciate your other pointers, too - using === to avoid type coercion, etc. Your time and expertise is much appreciated. – skwidbreth Aug 13 '15 at 21:19