Why doesn't Javascript validate my html code? - javascript

This is my first attempt at working with javascript and forms; for some reason my html website elements aren't being validated and I am not sure why. My goal with this form is trying to validate the elements that have an '*' next to them. For some reason the only element that is being validated is email and nothing else. Name, dates, the checkbox aren't. I have been trying to find a fix, but nothing seems to work.
<!doctype html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
<script src="script.js"></script>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
<input type="radio" name="tos" value="yes">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" type="submit" value="Submit">Submit</button>
<button class="btn-reset" type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
Here is the javascript that is being linked in the html. I am unsure whether the issue is with my html code or with my javascript.
// JavaScript Document
function validateForm()
{
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var dob = document.forms["myForm"]["DOB"].value;
var packages = document.forms["myForm"]["package"].value;
var arrival = document.forms["myForm"]["arrival"].value;
//var interest = document.forms["form"]["interest"].value;
var ToS = document.forms["myForm"]["tos"].value;
var checkbox = document.querySelector('input[name="interest"]:checked');
var matches = name.match(/\d+/g);
if (matches != null) {
alert("Name has a number in it!");
}
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (dob == "") {
alert("Date of Birth must not be empty");
return false;
}
if (arrival == "") {
alert("Arrival Date must not be empty");
return false;
}
if(ToS == false) {
alert("You must agree to the Terms of Service");
return false;
}
if(validateEmail(email) == false){
alert("Must enter a valid email");
}
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(dob != '' && !dob.match(re)) {
alert("Invalid date format");
return false;
}
if(arrival != '' && !arrival.match(re)) {
alert("Invalid arrival date format") ;
return false;
}
if(name.length >= 30){
alert("Name must be less than 30 characters!");
return false;
}
if(!checkbox){
alert("Please select an interest!");
return false;
}
}
function validateEmail(email)
{
return /\S+#\S+\.\S+/.test(email);
}

So I have no idea what your PHP form did, so I actually just pulled all the form code for now. There were a lot of little issues but honest mistakes. Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields. I combined some separate validations into if/else's since they were validations on the same field. I used ID's to make my life easier and since I dumped the form code. Feel free to swap back to what you want. I also updated your regex since the date field returns YYYY/MM/DD. Since this doesn't post anywhere you can play with it for a while, before tying back into your php form. I also pulled the check for 30 characters and added a max field length to name. You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof. There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started. Good Luck
<!doctype html>
<html>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input id="email" type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select id='package' name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span>
<input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
<input type="radio" name="tos" id="unaccepted" value="disagree">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>
</div>
<script>
// JavaScript Document
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dob = document.getElementById("dob").value;
//Select Box
var e = document.getElementById("package");
// Selected Item
var packages = e.options[e.selectedIndex].value;
var arrival = document.getElementById("arrival").value;
//var interest = document.getElementById("").value;
var tos = document.querySelector('input[name="tos"]:checked').value;
//var checkbox = document.getElementById("").value;;
var matches = name.match(/\d+/g);
var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;
if (!name) {
alert("Name must be filled out");
} else {
if (matches != null) {
alert("Name has a number in it!: " + name);
}
}
if (!email) {
alert("Email must be filled out");
} else {
if (validateEmail(email) == false) {
alert("Must enter a valid email: " + email);
}
}
if (!dob) {
alert("Date of Birth must not be empty");
} else {
if (!dob.match(re)) {
alert(" Dob has Invalid date format: " + dob);
}
}
if (!arrival) {
alert("Arrival Date must not be empty");
} else {
if (!arrival.match(re)) {
alert(" Dob has Invalid date format: " + arrival);
}
}
if (tos != "agree") {
alert("You must agree to the Terms of Service");
}
}
function validateEmail(email) {
return /\S+#\S+\.\S+/.test(email);
}
</script>
</body>
</html>

Related

Disabling a button on empty <select> list?

`I've created a form that allows a user to enter their details and have their first and last names displayed along with a numerical ID. There is a 'Delete' button allowing the user to remove whatever name they select.
by default, the 'Delete' button should be disabled until the <select> list is populated. If all names are deleted from the list - the 'Delete' button should disable again.
That's where im struggling. I cant get the 'Delete' button to enable when a name is added to the list.
Below is my HTML and JavaScript:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.value === 1;
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log("is remove being triggered??")
}
if (Member.options.length == ""){
Delete.disabled = true
}
else {
Delete.disabled = false
}
</script>
</body>
`
The reason why the Delete button is not enabling is because the code that is supposed to enable the Delete button is only run once, when the page loads.
Assuming that this is the code that is supposed to enable the button:
if (Member.options.length == 0){ // changed from Member.options.length == ""
Delete.disabled = true
} else {
Delete.disabled = false
}
This code is only run once, when the page loads and the JavaScript code is run. In order to enable the button properly, we need to run this code every time that Member.options.length changes. One way you can do this is place the code snippet above for disabling/enabling the Delete button inside the onclick listener for the save button and to re-check every time a new user is saved. You would have to add this snippet into every place in your code where Member.options.length could change (inside the listener for the delete button as well).
Full updated code:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.options.length == 0
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
if (Member.options.length == 0){
Delete.disabled = true
}
else {
Delete.disabled = false
}
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
if (Member.options.length == 0) {
Delete.disabled = true
}
else {
Delete.disabled = false
}
console.log("is remove being triggered??")
}
</script>
</body>
so if i understood correctly you want to toggle a button if a is populated
In that case you want to keep track of the options
You can use
document.querySelectoAll('options')
and store it in a variable
then write a function that check if there's a value in that variable and disable or enable the button based on that.
Here's a fiddle:
https://jsfiddle.net/skm7bcr6/15/

How do I add checks to make the code to display 'Password too short' and 'Height is not a number?'

I have to add checks to the checkSubmit() function so that it will give the following response
Passwords do not match
Passwords is too short(minimum 4 characters)
Height is not a number
I have managed the first one however I have no idea where to start with the other two. I'll post all the code just to be safe in case I missed something.
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
Do this for the second:
if (form['password'].value.length < 4) {
error.push("Password is too short");
}
And this for the third:
if (isNan(Number(form['height'].value))) {
error.push("Height is not a number");
}

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

Basic JavaScript validation not working

I'm trying to make a simple form with JavaScript validation. It has four fields: title, email address, rating and comments. As far as I know, the code I have here should work to validate the form and I should not be allowed to submit it but whenever I press the submit button none of the prompts appear and the browser submits the form. Could someone let me know where I am going wrong please? I'd imagine there is a simple solution or something I am forgetting but I'm pretty new to this so apologies if it's something very obvious.
The HTML and JavaScript code is:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["review"]["Title"].value;
var s=document.forms["review"]["Email"].value;
var t=document.forms["review"]["Rating"].value;
var c=document.forms["review"]["Comments"].value;
var atsym=s.indexOf("#");
var dotsym=s.lastindexOf(".");
if (e==null || e=="")
{
document.getElementById("valAlert").innerHTML="Please Enter a Title";
return false;
}
else if (s==null || s=="" || atsym<1 || dotsym<atsym+2 || dotsym+2>=s.length)
{
document.getElementById("valAlert").innerHTML="That is not a valid email address!";
return false;
}
else if (t=="0")
{
document.getElementById("valAlert").innerHTML="You must enter a rating";
return false;
}
else if (c==null || c=="")
{
document.getElementById("valAlert").innerHTML="You need to enter some kind of comment.";
return false;
}
else
{
alert ("Your review of " + t + "has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title">
</br>
</br>
Enter Email Address:
<input type="text" name="Email">
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
</body>
please make a null value check before doing the operations like below
var dotsym=s.lastindexOf(".");
Add the null check for variable 's'.Please check the function naming convention below
obj.lastindexOf(); TO obj.lastIndexOf(".");
You’ve said there were no errors, but you might just be missing them when the form submits and the console is cleared.
If you’re using Chrome/Chromium, you can enable breaking on exceptions in the Sources tab of the developer tools (the icon on the far right should be purple or blue):
In Firefox, it’s in the Debugger Options menu:
As #Rajesh says, the casing you have on lastindexOf is wrong; it should be lastIndexOf.
Now, let’s fix everything else up, starting with formatting:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var atsym = s.indexOf("#");
var dotsym = s.lastIndexOf(".");
if (e == null || e == "")
{
document.getElementById("valAlert").innerHTML = "Please Enter a Title";
return false;
}
else if (s == null || s == "" || atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length)
{
document.getElementById("valAlert").innerHTML = "That is not a valid email address!";
return false;
}
else if (t == "0")
{
document.getElementById("valAlert").innerHTML = "You must enter a rating";
return false;
}
else if (c == null || c == "")
{
document.getElementById("valAlert").innerHTML = "You need to enter some kind of comment.";
return false;
}
else
{
alert("Your review of " + t + " has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
</br>
</br>
Enter Email Address:
<input type="text" name="Email" />
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
</body>
You’re missing a DTD and a closing </html>, so add those:
<!DOCTYPE html>
<html>
…
</html>
Next, </br> doesn’t exist. It’s <br />.
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
<br />
<br />
Enter Email Address:
<input type="text" name="Email" />
<br />
<br />
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
<br />
<br />
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
<br />
<br />
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
Here:
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
the properties are valid JavaScript identifiers, so you can write them with the dot syntax:
var e = document.forms.review.Title.value;
var s = document.forms.review.Email.value;
var t = document.forms.review.Rating.value;
var c = document.forms.review.Comments.value;
You should probably give them clearer names, too; I think you used the wrong one in that last alert, and this will help:
var title = document.forms.review.Title.value;
var email = document.forms.review.Email.value;
var rating = document.forms.review.Rating.value;
var comments = document.forms.review.Comments.value;
Next, you don’t need elses when you’re returning from the if case no matter what, so you can drop those. The values of text inputs can never be null, so stop checking for those. It’ll also save some typing (or copying) to keep valAlert as a variable.
var atsym = email.indexOf("#");
var dotsym = email.lastindexOf(".");
var valAlert = document.getElementById("valAlert");
if (title === "") {
valAlert.innerHTML = "Please Enter a Title";
return false;
}
if (atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length) {
valAlert.innerHTML = "That is not a valid email address!";
return false;
}
if (rating == "0") {
valAlert.innerHTML = "You must enter a rating";
return false;
}
if (comments == "") {
valAlert.innerHTML = "You need to enter some kind of comment.";
return false;
}
alert("Your review of " + title + " has been submitted!");
Voilà! But wait; there’s more. The best things in life web development don’t need JavaScript, and this is no exception.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 validation</title>
</head>
<body>
<form>
<fieldset>
<label>
Enter title:
<input type="text" name="title" required />
</label>
<label>
Enter e-mail address:
<input type="email" name="email" required />
</label>
<label>
Please enter your rating:
<select name="rating" required>
<option>(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</label>
<textarea name="comments" rows="8" cols="40" placeholder="Comments" required></textarea>
</fieldset>
<fieldset>
<button class="button">Submit</button>
</fieldset>
</form>
</body>
</html>
I beg to differ on your comments. You are getting console errors. Specially, it is erroring out whenever you try to run the parsers on s and s is empty. You need to move the logic into the if clause AFTER you have verified it has a value:
else if (s == null || s == "") {
document.getElementById("valAlert").innerHTML = "Please enter an email address";
return false;
}
else if (s.indexOf("#") < 1 || s.lastindexOf(".") < s.indexOf("#")+ 2 || s.lastindexOf(".")+ 2 >= s.length) {
document.getElementById("valAlert").innerHTML = "This is not a valid email address!";
return false;
}
Here is a Fiddle

trouble validating various inputs with jQuery

for a class project I have to build a website for a pet store, featuring a pet grooming service. This involves a form, php and a mysql server on my localhost. I have been unable to correctly validate this form via a jQuery validator plugin for some unknown (to me) reason.
I've had no luck via regular jQuery code beyond getting the form to not submit blank input values. So as it is, anybody can put 'sadklfhsdk' in any of the fields (except for email, unless it has a '#') and it will validate and submit to the server.
So after I going through a couple of tutorials this is what I have so far:
The HTML:
<body>
<div id="h2Groom"><h2>Grooming Request Form</h2></div>
<form id="groom_form" method="post" action="insertPS.php">
<div id="result"></div>
<label for="firstName"><span>First Name:</span>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name" class="required"/>
</label>
<label for="lastName"><span>Last Name:</span>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name" class="required"/>
</label>
<label for="email"><span>Email Address:</span>
<span id="error"></span>
<input type="email" name="email" id="email" placeholder="Enter a Email"/>
</label>
<label for="phone"><span>Phone Number:</span>
<span id="error"></span>
<input type="text" name="phone" id="phone" placeholder="Enter a phone number" class="required"/>
</label>
<label for="address"><span>Address:</span>
<input type="text" name="address" id="address" placeholder="Enter your address" class="required"/>
</label>
<label for="city"><span>City:</span>
<input type="text" name="city" id="city" placeholder="Enter your city" />
</label>
<label for="state"><span>State:</span>
<input type="text" name="state" id="state" placeholder="Enter your state" class="required"/>
</label>
<label for="zipcode"><span>Zipcode:</span>
<input type="text" name="zipcode" id="zipcode" placeholder="Enter your zipcode" class="required"/>
</label>
<label for="petType"><span>Type of Pet:</span>
<ul>
<li><label><input name="petType" type="radio" value="dog" id="dog">Dog</label></li>
<li><label><input name="petType" type="radio" value="cat" id="cat">Cat</label></li>
<li><label><input name="petType" type="radio" value="bird" id="bird">Bird</label></li>
</ul>
</label>
<select id="breed" name="breed">
<option value="0">--Please Choose Dog Breed--</option>
<option value="AlaskanMal">Alaskan Malamute</option>
<option value="Bichon">Bichon Frise</option>
<option value="WelshCorgi">Corgi, Welsh</option>
<option value="Dalmation">Dalmation</option>
<option value="EnglishToySpan">English Toy Spaniel</option>
<option value="FrenchBull">French Bull Dog</option>
<option value="Greyhound">Greyhound</option>
<option value="Papillon">Papillon</option>
<option value="Rottweiler">Rottweiler</option>
<option value="YorkshireTerr">Yorkshire Terrier</option>
</select>
<label for="neut"><span>Check box if your pet has been neutered/spayed (leave unchecked if not).</span></label>
<ul>
<label>
<li><input type="checkbox" name="neut" id="neut" />Yes</li></label>
</ul>
<br />
<br />
<br />
<label for="petname"><span>Pet Name:</span>
<input type="text" name="petname" id="petname" placeholder="Enter your pet's name" class="required" />
</label>
<label for="petBday"><span>Pet's Birthday:</span>
<input type="date" id="petBday" name="petBday"/>
</label>
<span> </span>
<input type="submit" id="submitBttn" value="Submit" /><input type="reset" id="resetBttn" value="Reset" />
</form>
</body>
The jQUERY (except the script to send values to server, see jsfiddle link):
$(document).ready(function() {
$('input[name=petType]').click(function() {
if(this.id=='dog') {
$('#breed').show('slow');
}
else {
$('#breed').hide('slow');
}
});
$('input[name=phone]').blur(function() {
if (validatePhone('phone')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$('input[name=email]').blur(function() {
if (validateEmail('email')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$("#submitBttn").click(function() {
//get input field values
var user_firstName = $('input[name=firstName]').val();
var user_lastName = $('input[name=lastName]').val();
var user_email = $('input[name=email]').val();
var user_address = $('input[name=address]').val();
var user_phone = $('input[name=phone]').val();
var user_city = $('input[name=city]').val();
var user_state = $('input[name=state]').val();
var user_zipcode = $('input[name=zipcode]').val();
var user_petname = $('input[name=petname]').val();
var checked_radio = $('input:radio[name=petType]').is(':checked');
var user_neut = $('input:checkbox[name=neut]').is(':checked');
var user_breed = $('input:select[name=breed]').is(':selected');
var txtVal = $('#petBday').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
var proceed = true;
//Validation functions, executed when user hits "submit"
function validatePhone(phone) {
var a = document.getElementById(phone).value;
var filter = /^[0-9-+]+$/;
if (filter.text(phone)) {
return true;
}
else {
return false;
}
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
//declare regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); //is the format ok?
if(dtArray ==null)
return false;
//checks for mm/dd/yyyy format
dtMonth = dtArray[1];
dtDay = dtArray[3];
dtYear = dtArray[5];
if(dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if(dtDay > 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
EDIT: corrected if(filter.text()) to if(filter.test(phone)). None of my java validation code works.
validatePhone: filter.text should be spelled test

Categories

Resources