0

My school gave me a week to learn JavaScript. We started with form validation.

I was able to successfully figure out name and email address but I am unable to add the date validation that is required.

My code so far:

function formValidator() {
  // Make quick references to our fields
  var name = document.getElementById('name');
  var email = document.getElementById('email');

  // Check each input in the order that it appears in the form!
  if (isAlphabet(name, "Please enter only letters for your name")) {
    if (emailValidator(email, "Please enter a valid email address")) {
      return true;
    }
  }
  return false;
}

function notEmpty(elem, helperMsg) {
  if (elem.value.length == 0) {
    alert(helperMsg);
    elem.focus(); // set the focus to this input
    return false;
  }
  return true;
}

function isNumeric(elem, helperMsg) {
  var numericExpression = /^[0-9]+$/;
  if (elem.value.match(numericExpression)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

function isAlphabet(elem, helperMsg) {
  var alphaExp = /^[a-zA-Z]+$/;
  if (elem.value.match(alphaExp)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

function isAlphanumeric(elem, helperMsg) {
  var alphaExp = /^[0-9a-zA-Z]+$/;
  if (elem.value.match(alphaExp)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

function lengthRestriction(elem, min, max) {
  var uInput = elem.value;
  if (uInput.length >= min && uInput.length <= max) {
    return true;
  } else {
    alert("Please enter between " + min + " and " + max + " characters");
    elem.focus();
    return false;
  }
}

function madeSelection(elem, helperMsg) {
  if (elem.value == "Please Choose") {
    alert(helperMsg);
    elem.focus();
    return false;
  } else {
    return true;
  }
}

function emailValidator(elem, helperMsg) {
  var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
  if (elem.value.match(emailExp)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

//javascriptkit.com/script/script2/validatedate.shtml


function checkdate(input) {
  var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
  var returnval = false
  if (!validformat.test(input.value))
    alert("Invalid Date Format. Please correct and submit again.")
  else { //Detailed check for valid date ranges
    var monthfield = input.value.split("/")[0]
    var dayfield = input.value.split("/")[1]
    var yearfield = input.value.split("/")[2]
    var dayobj = new Date(yearfield, monthfield - 1, dayfield)
    if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
      alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
    else
      returnval = true
  }
  if (returnval == false) input.select()
  return returnval
}
<div id="form">
  <h1>Questions? Contact Us!</h1>
  <form onsubmit='return formValidator()'>
    <label for="name">Name:</label>
    <input type='text' id='name' /><br />
    <label for="email">Email:</label>
    <input type='text' id='email' /><br />
    <label for="date">Date: </label>
    <input type="text" id="date" required /> <br>
    <label for="message">Question:</label>
    <textarea name="message" rows="8" cols="20" required>Please make sure your question is at least five words.</textarea> <br>
    <input type='submit' value='Check Form' />
  </form>
</div>

I think I should change the function check date but I'm not sure what to do.

Thanks.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • https://www.informationbuilders.com/support/developers/javascript-validate-date-entry – drzounds Sep 02 '18 at 15:13
  • Perhaps change the type from text `type="text"` to date `type="date"` to start with. – Mark Schultheiss Sep 02 '18 at 15:44
  • Please study the following answer to another question which may assist you here. https://stackoverflow.com/a/6178341/125981 – Mark Schultheiss Sep 02 '18 at 15:47
  • I would add the semi-colons to the lines in the function you have also. i.e. where you have as an example `var returnval = false` use `var returnval = false;`, do for each line. – Mark Schultheiss Sep 02 '18 at 15:49
  • You should explain what is going wrong, e.g. a test input value, expected result and actual result. "unable to validate date" is not a very clear problem description. As an aside, when validating a date this way you only need to test the month. If the day is out of range, the month will change. If the month is out of range, it will change. The year can't be out of range. – RobG Sep 02 '18 at 23:15

1 Answers1

0

Wire up the date validation in your function.formValidator - I modified that function to use an isValid to avoid large numbers of nested validation. IF you want to ONLY work with one at a time, starting with name you could use that in the next as well by adding it to the start of each one, it skips if it is false:

if (isValid && !emailValidator(email, "Please enter a valid email address"))

Note the added ! on !emailValidator says to make isValid false if it fails.

function formValidator() {
  // Make quick references to our fields
  var name = document.getElementById('name');
  var email = document.getElementById('email');
  var mydate = document.getElementById('date'); // add this one
  var isValid = true; //added this (form level valid true/false)

  // Check each input in the order that it appears in the form!
  if (!isAlphabet(name, "Please enter only letters for your name")) {
    isValid = false;
  }

  if (!emailValidator(email, "Please enter a valid email address")) {
    isValid = false;
  }
  // check the date
  if (!checkdate(mydate)) {
    isValid = false;
    alert("bad date " + mydate.value);
  }
  return isValid;
}

function notEmpty(elem, helperMsg) {
  if (elem.value.length == 0) {
    alert(helperMsg);
    elem.focus(); // set the focus to this input
    return false;
  }
  return true;
}

function isNumeric(elem, helperMsg) {
  var numericExpression = /^[0-9]+$/;
  if (elem.value.match(numericExpression)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

function isAlphabet(elem, helperMsg) {
  var alphaExp = /^[a-zA-Z]+$/;
  if (elem.value.match(alphaExp)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

function isAlphanumeric(elem, helperMsg) {
  var alphaExp = /^[0-9a-zA-Z]+$/;
  if (elem.value.match(alphaExp)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

function lengthRestriction(elem, min, max) {
  var uInput = elem.value;
  if (uInput.length >= min && uInput.length <= max) {
    return true;
  } else {
    alert("Please enter between " + min + " and " + max + " characters");
    elem.focus();
    return false;
  }
}

function madeSelection(elem, helperMsg) {
  if (elem.value == "Please Choose") {
    alert(helperMsg);
    elem.focus();
    return false;
  } else {
    return true;
  }
}

function emailValidator(elem, helperMsg) {
  var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
  if (elem.value.match(emailExp)) {
    return true;
  } else {
    alert(helperMsg);
    elem.focus();
    return false;
  }
}

//javascriptkit.com/script/script2/validatedate.shtml


function checkdate(input) {
  var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
  var returnval = false;
  if (!validformat.test(input.value)) {
    alert("Invalid Date Format. Please correct and submit again.");
  } else { //Detailed check for valid date ranges
    var monthfield = input.value.split("/")[0];
    var dayfield = input.value.split("/")[1];
    var yearfield = input.value.split("/")[2];
    var dayobj = new Date(yearfield, monthfield - 1, dayfield);
    if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
      alert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
    } else {
      returnval = true;
    }
  }
  if (returnval == false) {
    input.select();
  }
  return returnval;
}
<div id="form">
  <h1>Questions? Contact Us!</h1>
  <form onsubmit='return formValidator()'>
    <label for="name">Name:</label>
    <input type='text' id='name' /><br />
    <label for="email">Email:</label>
    <input type='text' id='email' /><br />
    <label for="date">Date: </label>
    <input type="text" id="date" required /> <br>
    <label for="message">Question:</label>
    <textarea name="message" rows="8" cols="20" required>Please make sure your question is at least five words.</textarea> <br>
    <input type='submit' value='Check Form' />
  </form>
</div>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • Note I stayed with your initial "text" type here as that was not a part of the question. I also did not address the "Question" input which is an entirely new question but would appear to need work given the "text" it contains. – Mark Schultheiss Sep 02 '18 at 16:23
  • @RobG since I did provide explanation your comment is invalid really – Mark Schultheiss Sep 03 '18 at 12:22