3

I am new to javascript and I am facing the following issue: I made a simple date accepting form which checks the format before submission. In case the entered date is not in the desired format, it shows an error. Now, I replace the submit button on the form with a link using another javascript function. I link it to javascript:document.forms[0].submit(). This time, the format checking function is not called during form submission. It gets submitted without the check. It would be nice if someone could tell me how to overcome this issue.

function checkDate() {
  var date = document.getElementById("date");
  var dt = date.value;
  var flag = 1;
  var msg = "";
  var errorHere = document.getElementById("spam");
  for (var i = 0; i < dt.length; i++) {
    if (i == 2 || i == 5) {
      if (dt[i] != '-') {
        flag = 0;
        break;
      }
      continue;
    }
    if (dt[i] < '0' || dt[i] > '9') {
      flag = 0;
      break;
    }
  }
  if (dt.length != 10) flag = 0;
  if (dt.length == 0) flag = -1;
  if (flag == 0)
    msg += "Invalid format.";
  else if (flag == -1)
    msg += "Empty field."
  else msg += "OK.";
  errorHere.firstChild.nodeValue = msg;
  if (flag == 1) return true;
  else return false;
}

function submitter() {
  var abc = confirm("Would you like to switch to link?");
  if (abc == true) {
    var i = 0,
      now;
    while (++i) {
      now = document.getElementsByTagName("input")[i];
      if (!now) return;
      if (now.type == "submit") break;
    }
    var latest = document.createElement("a");
    latest.href = "javascript:document.forms[0].submit()";
    var text = document.createTextNode(now.value);
    latest.appendChild(text);
    now.parentNode.replaceChild(latest, now);
  }
}
window.onload = submitter;
<head>
  <script type="text/javascript" src="date.js">
  </script>
</head>

<body>
  <h1>Date checker</h1>
  <form action="eventssearch.php" method="post" onsubmit="return checkDate();">
    <p>
      <label for="date">Date in the format DD-MM-YYYY:</label>
      <br />
      <input type="text" id="date" name="date" />
      <input type="submit" value="Check" />
      <br />(example 01-01-1970)
      <p id="spam"></p>
    </p>
  </form>
</body>

Gramercy...

George Kagan
  • 5,913
  • 8
  • 46
  • 50
americast
  • 37
  • 2
  • 8
  • Did it. Now the line is `
    `, but it's still not working. Now, the checking function is not wokring even when submitted using the normal submit button...Gramercy...
    – americast Oct 15 '16 at 18:04
  • You can try it below. You don't need the semi-colon there. – Jecoms Oct 15 '16 at 18:04
  • There was an error with trying to set a nodeValue of a null reference. I switched it to set the innerText of your "spam" span. It works now. – Jecoms Oct 15 '16 at 18:09
  • Still not working... – americast Oct 15 '16 at 18:11
  • I updated the code to work with the link. – Jecoms Oct 15 '16 at 18:20
  • Not your problem, but a UX issue — When I receive a date on the server that the user typed in the browser, I attempt to parse what they typed in about a dozen ways, starting with how I asked for it. So if I want `MM/DD/YYYY` I try that first, then `MM-DD-YYYY`, `YYYY-MM-DD` etc, all the way to `monthname DD, YYYY`, and only reject if I can't figure it out. This is _much_ more friendly to the user, and it's not a burden to the server which has plenty of processing power. – Stephen P Oct 15 '16 at 19:24
  • @americast I was mistaken about the onsubmit "return". You do need to include it or the false value returned by the function will be discarded and the form will still submit. Yay javascript! :) – Jecoms Oct 15 '16 at 20:58

1 Answers1

3

Instead of using

"javascript:document.forms[0].submit()"

you can call your own function that will call the validation function and submit if the form is valid:

`javascript:singleSumbitFunc()`

This same function can then be set as the form's onsubmit function as well.

<form action="eventssearch.php" method="post" onsubmit="return singleSubmitFunc()">

Example function:

function singleSubmitFunc() {
  var form = document.forms[0];

  // here is the where your validation function is called
  // .call() is to set the form as 'this'
  var formIsValid = checkDate.call(form);

  if (formIsValid) {
    form.submit();
  } 

  return false; // this prevents normal submit if called by form
}

The reason you need to do this is because the submit event is not fired when using .submit() in your code/link. The function used in this example will call the desired function directly.

The onsubmit handling was adapted from this SO answer

function checkDate() {
  document.getElementById('checkDateFeedBack').innerText = 'checkDate() fired! at ' + new Date().toLocaleString();
  var date = document.getElementById("date");
  var dt = date.value;
  var flag = 1;
  var msg = "";
  var errorHere = document.getElementById("spam");
  for (var i = 0; i < dt.length; i++) {
    if (i == 2 || i == 5) {
      if (dt[i] != '-') {
        flag = 0;
        break;
      }
      continue;
    }
    if (dt[i] < '0' || dt[i] > '9') {
      flag = 0;
      break;
    }
  }
  if (dt.length != 10) flag = 0;
  if (dt.length == 0) flag = -1;
  if (flag == 0)
    msg += "Invalid format.";
  else if (flag == -1)
    msg += "Empty field."
  else msg += "OK.";
  errorHere.innerText = msg;
  if (flag == 1) return true;
  else return false;
}

function singleSubmitFunc(event) {
  var form = document.forms[0];

  // here is the where your validation function is called
  // .call() is to set the form as 'this'
  var formIsValid = checkDate.call(form);
  
  if (formIsValid) {
    form.submit();
    document.getElementById('checkDateFeedBack').innerText = 'Valid form has been submitted!';
  } 
  
  return false; // prevent normal submit if called by form      
}

function submitter() {
  var abc = confirm("Would you like to switch to link?");
  if (abc == true) {
    var i = 0,
      now;
    while (++i) {
      now = document.getElementsByTagName("input")[i];
      if (!now) return;
      if (now.type == "submit") break;
    }
    var latest = document.createElement("a");
    latest.href = "javascript:singleSubmitFunc()"; // calls custom form submit function
    var text = document.createTextNode(now.value);
    latest.appendChild(text);
    now.parentNode.replaceChild(latest, now);
  }
}
window.onload = submitter;
.error {
  color: #c00;
  font-weight: bold;
}
<head>
  <script type="text/javascript" src="date.js">
  </script>
</head>

<body>
  <h1>Date checker</h1>
  <form action="eventssearch.php" method="post" onsubmit="return singleSubmitFunc()">
    <p>
      <label for="date">Date in the format DD-MM-YYYY:</label>
      <br />
      <input type="text" id="date" name="date" />
      <input type="submit" value="Check" />
      <br />(example 01-01-1970)
      <p id="spam"></p>

      <p id="checkDateFeedBack"></p>
    </p>
  </form>
</body>
Community
  • 1
  • 1
Jecoms
  • 2,558
  • 4
  • 20
  • 31
  • In the code which you have provided, `checkDate()` is not being fired when the submit button has been replaced with a link using the function `submitter()`...Gramercy... – americast Oct 15 '16 at 18:22
  • I just added the function to handle the link submission. It now will call the onsubmit function even when using the link. – Jecoms Oct 15 '16 at 18:23
  • Thanx! It works now....but isn't there any way in which we could do it using just one function? I mean, is it not possible to call the `onsubmit` part of the `
    ` using the link?
    – americast Oct 15 '16 at 18:28
  • Yes you can. I updated the code to use the same function in your link and onsubmit. – Jecoms Oct 15 '16 at 19:00
  • @americast When submitting via code / that link, no submit event is created, so the onsubmit function won't fire. You have to call it directly. – Jecoms Oct 15 '16 at 19:07
  • Also, using `errorHere.firstChild.nodeValue` does not cause any problem. It works fine, at least in my browser. My logic was that `errorHere` refers to the element "spam" whose child is text, and `nodeValue` returns the text content when pointed to text (and null when pointed to some other element). Hence, it should work fine.....But I would definitely agree that using `innerText` is also a good approach...Gramercy... – americast Oct 16 '16 at 04:08
  • Ah. It just wasn't working in the snippet so I changed it. – Jecoms Oct 16 '16 at 04:11