Phone or Email Validation
HTML
<form autocomplete="off" method="post" action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi" action="" id="hw4Form" name="hw4Form"><br>
<!-- Reformat 10 digits (in a row) to xxx-xx-xxxx: -->
<br>
<label for="phone">Phone</label>
<input type="text" id="phone" name="phone" maxlength="12" value="">
<!--<input type="text" id="phone" name="phone" pattern="\d{3}-\d{3}-\d{4}"
type="text">-->
<br>
<span id="msg">Need 10 digits (in a row)</span>
<br>
<br>
<!-- Email pattern = .+, one or more characters; @ then an '@' sign; .+ then one or more characters; \. then a dot; .+ then one or more characters after the dot-->
<label for="email">Email</label>
<input placeholder="Email address" name="email" id="email" type="email" pattern=".+@.+\..+"><br>
<br>
<span id="error"></span>
<button type="submit" id="submitBtn" name="submit">Register Me!</button><br>
<legend>About You</legend>
</fieldset>
<br>
</form>
JavaScript
/*-------------------------------------------------------------------------------------------------
REFORMAT PHONE NUMBER
-------------------------------------------------------------------------------------------------*/
/*
* Your validation should confirm that it's a ten-digit number,
* regardless of the punctuation used, and format it in the input field
* as xxx-xxx-xxxx. You may do this by applying the formatting live
* (difficult), or waiting until the user has finished typing in the
* field (onchange or onblur) and then reformat the string (easier). It's up to you.
*/
function reformat() {
console.log("Reformatting digits.");
//Grab the necessary elements and/or values
var val = document.getElementById("phone").value;
var output=document.getElementById("msg");
// Got this from Rob...SWEET! Allows only numbers!
phone.value = val.replace(/[^\d]/, '');
if (val.match(/^(\d{3})(\d{3})(\d{4})$/)) {
phone.value = val.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
} else {
output.innerHTML = "Need 10 digits (in a row)";
}
}
// Add event handlers
document.getElementById("phone").onkeyup = reformat;
/*-------------------------------------------------------------------------------------------------
Either PHONE NUMBER or EMAIL is REQUIRED
-------------------------------------------------------------------------------------------------*/
var phone = document.getElementById("phone");
var email = document.getElementById("email");
var myForm = document.getElementById("hw4Form");
//var myForm = document.forms[0];
//console.log(myForm);
//error.innerHTML = "";
hw4Form.addEventListener("submit", function(e){
if((phone.value == "") && (email.value == "")){
//alert("Either phone number or email are required");
error.innerHTML = "Error: You Must Enter an Email or Phone Number!";
...