Form Submission failed - javascript

I have an issue while submitting a form its giving me error that >validateform()is not defined
before it was working.
It is loan application in which I have to send an email once user submit form with correct details and also generate random 4 digit no which will be in email which user will receive
<script src="https://smtpjs.com/v3/smtp.js">
## Heading ##
function validateForm() {
let name = document.forms["myForm"]["fullName"].value;
let email = document.forms["myForm"]["email"].value;
let pan = document.forms["myForm"]["pan"].value;
let lamount = document.forms["myForm"]["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
const mybtn = document.getElementById('btn');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
let number1 = num1.innerText;
let number2 = num2.innerText;
enter code here
mybtn.addEventListener("click", () => {
//
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res == sum_result) {
alert("correct");
}
else {
alert("Incorrect")
}
window.location.reload();
});
if (name == "" || regName.test(name)) {
alert("Name must be filled out");
return false;
}
if (email == "" || !regEmail.test(email)) {
alert("Please enter a valid e-mail address.");
return false;
}
if (pan == "" || !regPan.test(pan)) {
alert("Please enter a valid PAN no.");
return false;
}
//OTP generation
const generateOtp = () =>{
let otp = "";
for(let i=0 ; i < 4 ; i++){
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
console.log("OTP:", generateOtp());
}
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "....",
// To: document.getElementById("email").value,
// From: "....#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
</script>
</head>
<body>
<div class="form-container">
<h1>Loan Application Form</h1>
<form name="myForm" method="post" action="thankyou.html" onsubmit="validateForm();">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span
class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span
class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span
class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span
class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>

You have many issues
You do not have a closing </script> for your <script src="https://smtpjs.com/v3/smtp.js"> and a starting <script> for your code.
Please try to use the snippet editor [<>] and remove the "enter code here" and ## Heading ##
You need to use the submit event and e.preventDefault is stopping the submit. I changed name="myForm" to id="myForm", forms do not need names
You are adding event listeners in the validation.
You were missing the refresh function
Here is what I believe you need
const generateOtp = () => {
let otp = "";
for (let i = 0; i < 4; i++) {
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
document.getElementById('bttn').addEventListener("click", e => {
e.preventDefault();
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
})
document.getElementById("myForm").addEventListener("submit", (e) => {
const form = e.target;
let name = form["fullName"].value;
let email = form["email"].value;
let pan = form["pan"].value;
let lamount = form["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
let number1 = num1.innerText;
let number2 = num2.innerText;
let errors = [];
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res != sum_result) errors.push("Sum not correct");
if (name == "" || regName.test(name)) errors.push("Name must be filled out");
if (email == "" || !regEmail.test(email)) errors.push("Please enter a valid e-mail address.");
if (pan == "" || !regPan.test(pan)) errors.push("Please enter a valid PAN no.");
if (errors) {
alert(errors.join("\n"));
e.preventDefault();
return
}
//OTP generation
console.log("OTP:", generateOtp()); // not sure what you want with this
// sendEmail()
})
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "...",
// To: document.getElementById("email").value,
// From: "...#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
<script src="https://smtpjs.com/v3/smtp.js"></script>
<div class="form-container">
<h1>Loan Application Form</h1>
<form id="myForm" method="post" action="thankyou.html">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>

Related

External js file not working with HTML file

Currently I am building a website which this page uses an external javascript file, one of the main function is that in the form if the user does not enter anything or enter the wrong value and clicks on the submit button, a error message will show up above each section, but unfortunately mine when I click on the submit button it will still submit and will not show any error, I suspect that the Javascript file is not linked properly but I did set the path correctly as you can see in the picture and the on the HTML page.
HTML File:
<meta charset="utf-8" />
<meta name="description" content="Demonstrates some basic HTML content elements and CSS" />
<meta name="keywords" content="html, css" />
<meta name="author" content="Jordan Siow" />
<link rel = "stylesheet" type = "text/css" href = "styles/style.css"/>
<script type="text/JavaScript" src="scripts/apply.js"></script>
<title>Apply </title>
<section class="front_title">
<p> Company XIT <img src="styles/images/logo.png" alt="logo" height="70" width="250"/>
</p>
</section>
<section class="topnav">
<table>
<tr>
<td >
Main
</td>
<td >
Jobs
</td>
<td id="current">
Apply
</td>
<td>
About
</td>
<td>
Enhancements
</td>
</tr>
</table>
</section>
<section id="style_apply">
<h2>Submit your Application!</h2>
<form method="post" id="apply_form" action="https://mercury.swin.edu.au/it000000/formtest.php">
<p><span id="job_id_error" class="error"></span></p>
<p><label for="jobid">Job Reference Number</label>
<input type="text" name="jobid" id="jobid" maxlength="5" pattern="[0-9]{5}" /></p>
<p><span id="firstname_error" class="error"></span></p>
<p><label for="firstname">First Name</label>
<input type ="text" name="First Name" id="firstname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<p><span id="lastname_error" class="error"></span></p>
<p><label for="lastname">Last Name</label>
<input type ="text" name="Last Name" id="lastname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<br/>
<p><span id="dob_error" class="error"></span></p>
<p><label for="dateofbirth">Date of Birth</label>
<input type="date" name="Date of Birth" id="dateofbirth" /></p>
<br/>
<br/>
<label>Gender</label>
<p><span id="gender_error" class="error"></span></p>
<fieldset id="gender">
<label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" />
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Others</label>
<input type="radio" id="other" name="Gender" value="other"/>
<label for="rathernotsay">Rather Not Say</label>
<input type="radio" id="rathernotsay" name="Gender" value="rathernotsay"/>
</fieldset>
<br/>
<div id="fieldset_label">
<label>Address Information</label>
</div>
<fieldset>
<p><span id="streetaddress_error" class="error"></span></p>
<p><label for="streetaddress">Street address</label>
<input type="text" name="Address" id="streetaddress" maxlength="40" "/></p>
<p><span id="suburb_error" class="error"></span></p>
<p><label for="suburb">Suburb/town</label>
<input type="text" name= "Suburb" id="suburb" maxlength="40" /></p>
<p><span id="state_error" class="error"></span></p>
<p><label for="state">State</label>
<select id="state" name="State">
<option value="">Please select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select></p>
<p><span id="postcodr_error" class="error"></span></p>
<p><label for="postcode">Postcode</label>
<input type="text" name= "Postcode" id="postcode" maxlength="4" pattern="\d{4}" placeholder="Postcode"/></p>
</fieldset>
<br/>
<p><span id="email_error" class="error"></span></p>
<p><label for="email">Email</label>
<input type="text" name="Email Address" id="email" /></p>
<p><span id="phonenumber_error" class="error"></span></p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="Phone Number" id="phonenumber" maxlength="12" pattern="[0-9]{8-12}" ></p>
<label>Skill list</label>
<fieldset>
<p><span id="skill_error" class="error"></span></p>
<label for="skill1">Web development languages</label>
<input type="checkbox" id="skill1" name="Skill 1" value="skill"/>
<label for="skill2">Data Management abilities</label>
<input type="checkbox" id="skill2" name="Skill 2" value="skill"/>
<label for="skill3">Others</label>
<input type="checkbox" id="skill3" name="Other" value="skill"/>
<br/>
<br/>
<section>
<label for="comm" style="display:block">Other skillset</label>
<textarea class="comments" id="comm" name="Comments" rows="5" cols="50" placeholder="Other skillsets..."></textarea>
</section>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="align_center">
<p><span id="error_check" class="error"></span></p>
<input type="submit" value="Submit Application"/>
<input type="reset" value="Reset Application form"/>
</div>
</form>
</section>
<br/>
<br/>
<br/>
<br/>
<footer class = "footer_text">
<hr/>
<p>
<strong>©</strong>
<a class="footer_text" href="http://www.swinburne.edu.au/">
Swinburne Universty of Technology
</a>
</p>
<p>  
 
<strong>Done by:</strong> <a class="footer_text" href="mailto:103173691#student.swin.edu.au">
Jordan Siow</a>
</p>
</footer>
JS File:
/* To Validate the Form */
function validate(){
// Initialises the result variable
var result = true;
// Intialises the error tags
var job_id_error = document.getElementById("job_id_error");
job_id_error.innerHTML = "";
var firstname_error = document.getElementById("firstname_error");
firstname_error.innerHTML = "";
var lastname_error = document.getElementById("lastname_error");
lastname_error.innerHTML = "";
var dob_error = document.getElementById("dob_error");
dob_error.innerHTML = "";
var gender_error = document.getElementById("gender_error");
gender_error.innerHTML = "";
var streetaddress_error = document.getElementById("streetaddress_error");
streetaddress_error.innerHTML = "";
var suburb_error = document.getElementById("suburb_error");
suburb_error.innerHTML = "";
var state_error = document.getElementById("state_error");
state_error.innerHTML = "";
var postcode_error = document.getElementById("postcode_error");
postcode_error.innerHTML = "";
var email_error = document.getElementById("email_error");
email_error.innerHTML = "";
var phonenumber_error = document.getElementById("phonenumber_error");
phonenumber_error.innerHTML = "";
var skill_error = document.getElementById("skill_error");
skill_error.innerHTML = ""
// If there is an error in the input it will set the result to false and displays an error message
// To get the variables from the form and will chgeck the given rules
var jobid = document.getElementById("jobid").value;
if (jobid == ""){
job_id_error.innerHTML = "Job Reference Number must not be blank";
result = false;
}
var firstname = document.getElementById("firstname").value;
if (!firstname.match(/^[a-zA-Z]+$/) || firstname.value == ""){
firstname_error.innerHTML = "First name must only contain alphabetic characters";
alert("First name must only contain alphabetic characters")
result = false;
}
var lastname = document.getElementById("lastname").value;
if (!lastname.match(/^[a-zA-Z\-]+$/) || lastname.value == ""){
lastname_error.innerHTML = "Last name must only contain aphabetic characters";
result = false;
}
var dateofbirth = document.getElementById("dateofbirth").value;
if (!dateofbirth.match(/\d{2}\/\d{2}\/\d{4}/)){
dob_error.innerHTML = "Invalid Date of Birth";
result = false;
}
var age = calculate_age(dateofbirth);
if (!isFinite(age) || isNaN(age)) {
dob_error.innerHTML = "Your Date of Birth role is not Available.";
result = false;
}
else if (age < 21 || age > 70) {
dob_error.innerHTML =
"You must be between 21 and 70 years old to apply.";
result = false;
}
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var other = document.getElementById("other").checked;
var rathernotsay = document.getElementById("rathernotsay").checked;
if (!(male || female || other || rathernotsay)) {
gender_error.innerHTML = "Please select a gender.";
result = false;
}
var streetaddress = document.getElementById("streetaddress").value;
if (streetaddress == "") {
streetaddress_error.innerHTML = "You must enter a street address.";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (suburb == "") {
suburb_error.innerHTML = "You must enter a suburb or town";
result = false;
}
var postcode = Number(document.getElementById("postcode").value);
if (postcode == "") {
postcode_error.innerHTML = "You must select a postcode";
result = false;
}
var state = document.getElementById("state").value
if (state == "") {
state_error.innerHTML = "You must select a state";
result = false;
} else {
var tempMsg = validate_postcode(state, postcode);
if (tempMsg != "") {
state_error.innerHTML = tempMsg;
result = false;
}
}
var email = document.getElementById("email").value;
if (email == "") {
email_error.innerHTML = "You must enter an email address";
result = false;
}
var phonenumber = document.getElementById("phonenumber").value;
if (phonenumber == "") {
phonenumber_error.innerHTML = "You must enter a phone number";
result = false;
}
if (result){
storeBooking(firstname, lastname, dateofbirth, male, female, other, rathernotsay, streetaddress, suburb, state, postcode, email, phonnumber)
}
if (!result) {
document.getElementById("error_check").innerHTML = "Please correct all of the errors given above.";
}
return result;
}
/**
* calcualte age from date of birth
*/
function calculate_age(dateofbirth) {
var today = new Date();
var DateOfBirth = new Date(dateofbirth);
// get the difference between the years
var age = today.getFullYear() - DateOfBirth.getFullYear();
// get the difference between the months
var month = today.getMonth() - DateOfBirth.getMonth();
// if the dateofbirth month and day is earlier in the year
if (month < 0 || (month === 0 && today.getDate() < DateOfBirth.getDate())) {
age--; // remove a year
}
return age;
}
function validate_postcode(state, postcode) {
var errMsg = "";
switch (state) {
case "vic":
if (!((postcode >= 3000 && postcode <= 3999) || (postcode >= 8000 && postcode <= 8999))) {
errMsg += "Post Code not in Victoria.";
}
break;
case "nsw":
if (!((postcode >= 1000 && postcode <= 2599) || (postcode >= 2619 && postcode <= 2899) || (postcode >= 2921 && postcode <= 2999))) {
errMsg += "Post Code not in New South Wales.";
}
break;
case "qld":
if (!((postcode >= 4000 && postcode <= 4999) || (postcode >= 9000 && postcode <= 9999))) {
errMsg += "Post Code not in Queensland.";
}
break;
case "nt":
if (!(postcode >= 800 && postcode <= 999)) {
errMsg += "Post Code not in Northern Territory.";
}
break;
case "wa":
if (!(postcode >= 6000 && postcode <= 6999)) {
errMsg += "Post Code not in Western Australia.";
}
break;
case "sa":
if (!(postcode >= 5000 && postcode <= 5999)) {
errMsg += "Post Code not in Southern Australia.";
}
break;
case "tas":
if (!(postcode >= 7000 && postcode <= 7999)) {
errMsg += "Post Code not in Tasmania.";
}
break;
case "act":
if (!((postcode >= 200 && postcode <= 299) || (postcode >= 2600 && postcode <= 2618) || (postcode >= 2900 && postcode <= 2920))) {
errMsg += "Post Code not in Australian Capital Territory.";
}
break;
default:
errMsg = "Post Code not Valid.";
}
return errMsg;
}
/**
* Prefill the form from exisitng session data
*/
function prefill_id() {
var jobId_input = document.getElementById("jobid");
if (localStorage.jobId != undefined) {
// hidden input to submit details
jobId_input.value = localStorage.jobId;
jobId_input.readOnly = true;
} else {
jobId_input.readOnly = false;
}
}
/**
* Prefill the form from exisitng session data
*/
function prefill_form() {
prefill_id();
if (sessionStorage.firstname != undefined) {
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("dateofbirth").value = sessionStorage.dateofbirth;
document.getElementById("streetaddress").value = sessionStorage.streetaddress;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("phonenumber").value = sessionStorage.phonenumber;
switch (sessionStorage.gender) {
case "male":
document.getElementById("male").checked = true;
break;
case "female":
document.getElementById("female").checked = true;
break;
case "other":
document.getElementById("other").checked = true;
break;
case "rathernotsay":
document.getElementById("rathernotsay").checked = true;
break;
}
var skills = sessionStorage.skills;
document.getElementById("skill1").checked = skills.includes("skill1");
document.getElementById("skill2").checked = skills.includes("skill2");
document.getElementById("skill3").checked = skills.includes("skill3");
}
}
/**
* Store Job ID for pre fill in application form
*/
function storeJobId1() {
localStorage.jobId = document.getElementById("job1_id").innerHTML;
}
function storeJobId2() {
localStorage.jobId = document.getElementById("job2_id").innerHTML;
}
/**
* Store values for session
*/
function storeBooking(skill1, skill2, skill3, comm, firstname,
lastname, dateofbirth, streetaddress, suburb, state, postcode, email, phonenumber, male, female, other) {
// store values in sessionStorage
var skill_string = "";
if (skill1) {
skill_string = "skill1";
}
if (skill2) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill2";
}
if (skill3) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill3";
}
sessionStorage.skills = skill_string;
sessionStorage.firstname = firstname;
sessionStorage.lastname = lastname;
sessionStorage.dateofbirth = dateofbirth;
sessionStorage.streetaddress = streetaddress;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = ;
sessionStorage.email = email;
sessionStorage.phonenumber = phonenumber;
sessionStorage.comm = comm;
if (male) {
sessionStorage.gender = "male";
} else if (female) {
sessionStorage.gender = "female";
} else if (other) {
sessionStorage.gender = "other";
} else if (rathernotsay) {
sessionStorage.gender = "rathernotsay";
}
}
/*
This function is called when the browser window loads
it will register functions that will respond to browser events
*/
function init() {
if (document.title == "Available Jobs") {
document.getElementById("job1_apply").onclick = storeJobId1;
document.getElementById("job2_apply").onclick = storeJobId2;
} else if (document.title == "Application Form") {
prefill_form();
// register the event listener to the form
document.getElementById("apply_form").onsubmit = validate;
document.getElementById("apply_form").onreset = function () {
localStorage.clear();
prefill_id();
;}
}
}
window.onload = init;
I think you should check out this article: preventDefault() Event Method
When clicked, you should prevent the default behavior.
<script type="text/JavaScript" src="scripts/apply.js"></script>
Add the above script tag just before closing of body tag, it it best practice.
put a console.log("js file linked"); inside js file to test whether its linked or not.
Feel free to ask if it didn't work...
In the comments you mentioned
my friend told me its got to do with the last line in the js file "window.onload = init();
Your friend is correct - not sure if this is the only relevant thing, but here you are first running the function init() and the return value of that function is being saved into window.onload. Check out this example code:
function init() {
console.log(document.readyState);
}
window.onload = init();
console.log("Window onload is", window.onload);
Here init is run immediately and the return value of init will be saved to window.onload. This prints
loading
apply.js:315 Window onload is null
Instead, you should add a reference to the init function, so that the value of window.onload is your init function itself, not the return value; so the correction would be
function init() {
console.log(document.readyState);
}
window.onload = init;
console.log("Window onload is", window.onload);
// this one prints out
// Window onload is ƒ init() {console.log(document.readyState);}
// apply.js:311 complete
The "document.readyState" is used to check if the document has been loaded and parsed.

validity API to validate a form

I'm trying to validate a form with validity API, but have some issues (2 to be precise) . One for valueMissing where the textContent couldn't be displayed and the second when submitting the form (all fiels are corect then) : nothing happen, I can't see the console.log. Here is the code
html
const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
// function valid() : allow sending form after checking it
function valid(e) {
e.preventDefault();
let isFormOk = true;
let fname = document.getElementById('fname');
let missFname = document.getElementById('fname_missing');
let firstNameValue = document.getElementById('fname').value;
let email = document.getElementById('email');
let missEmail = document.getElementById('email_missing');
let emailValue = document.getElementById('email').value;
let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'\s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
let emailValid = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//Validate the firstname :
if (fname.validity.valueMissing) { //if the field is empty
missFname.textContent = 'Enter your firstname please!';
missFname.style.color = 'red';
isFormOk = false;
}
if (fnameValid.test(fname.value) == false) { // if the format is incorrect
missFname.textContent = 'Incorrect format';
missFname.style.color = 'black';
isFormOk = false;
}
//Validate the email :
if (email.validity.valueMissing) {
missEmail.textContent = 'Email missing';
missEmail.style.color = 'red';
isFormOk = false;
}
if (emailValid.test(email.value) == false) {
missEmail.textContent = 'Incorrect format';
missEmail.style.color = 'black';
isFormOk = false;
}
if (isFormOk) {
let contact = {
firstNameValue,
emailValue
};
console.log(contact);
}
<form novalidate id="myForm">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" required>
<span id="fname_missing"></span>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" required>
<span id="email_missing" class="errorMail" aria-live="polite"></span>
</div>
<div class="form-group">
<button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>
const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
// function valid() : allow sending form after checking it
function valid(e) {
e.preventDefault();
let isFormOk = true;
let fname = document.getElementById('fname');
let missFname = document.getElementById('fname_missing');
let firstNameValue = document.getElementById('fname').value;
let email = document.getElementById('email');
let missEmail = document.getElementById('email_missing');
let emailValue = document.getElementById('email').value;
let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'\s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
let emailValid = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//Validate the firstname :
if (fname.validity.valueMissing) { //if the field is empty
missFname.textContent = 'Enter your firstname please!';
missFname.style.color = 'red';
isFormOk = false;
}
if (fnameValid.test(fname.value) == false) { // if the format is incorrect
missFname.textContent = 'Incorrect format';
missFname.style.color = 'black';
isFormOk = false;
}
//Validate the email :
if (email.validity.valueMissing) {
missEmail.textContent = 'Email missing';
missEmail.style.color = 'red';
isFormOk = false;
}
if (emailValid.test(email.value) == false) {
missEmail.textContent = 'Incorrect format';
missEmail.style.color = 'black';
isFormOk = false;
}
if (isFormOk) {
let contact = {
firstNameValue,
emailValue
};
missEmail.style.display = 'none';
missFname.style.display = 'none';
console.log(contact);
}
return isFormOk;
}
<form novalidate id="myForm">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" required>
<span id="fname_missing"></span>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" required>
<span id="email_missing" class="errorMail" aria-live="polite"></span>
</div>
<div class="form-group">
<button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>
There is a curly brace missing in javascript function. Check this if it answers your question.

Validation for input value in javascript

I'm trying to use validation on input field for Employee salary
calculation form by using javascript.
The calculation code works fine, however it can't validate input field before proceeding with calculation.
Here the code.
function validateForm() {
var x = document.forms["myForm"]["employeename"]["employeeno"].value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
}
function paySalary() {
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary );
}
<body>
<form name="myForm" action="" onsubmit="return checkForm(this)" method="post">
<label>Employee Name :</label>
<input id="employeename" value=""><br>
<label>Employee No :</label>
<input id="employeeno" value=""><br>
<label>Rate of pay :</label>
<input id="rate" value=""><br>
<label>Hours Work :</label>
<input id="hours" value=""><br>
<br>
<button id="submit" onclick="paySalary()" >Submit</button>
</form>
<br>
<br>
</body>
The paySalary() function will be executed as soon as you click the submit button and before the form validation. What you can do is writting the validateForm() inside the paySalary() function. If the conditions pass the test then continue..
function validateForm() {
var x = document.getElementById("employeeno").value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
return true;
}
function paySalary() {
// If the form is not valid: stop execution
if(!validateForm()) {
return;
}
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary )
}
<body>
<form name="myForm" action="" onsubmit="return paySalary()" method="post">
<label>Employee Name :</label>
<input id="employeename" value="Bob"><br>
<label>Employee No :</label>
<input id="employeeno"><br>
<label>Rate of pay :</label>
<input id="rate" value="0"><br>
<label>Hours Work :</label>
<input id="hours" value="0"><br>
<br>
<button id="submit">Submit</button>
</form>
<br>
<br>
</body>

JS send message on correct input

I have a submit form that users are using to register:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="form" onSubmit="return validate(this);">
<div class="form-group">
<input type="text" id="name" name="name" class="inputs" /><br />
<input type="text" id="email" name="email" class="inputs" /><br />
<input type="password" id="password" name="password" class="inputs" />
</div>
<input type="submit" class="btn1" name="register" value="Register" />
</form>
The JS code is checking if the data is entered correctly. If the user enters incorrect date the JS code is showing a message. Now I want to show a message when the data is entered correctly. I tried to add a row like if (errors.length < 0) but this didn't work. The JS code sends me the message for the "correct input" and the message "Dont use symbols...\n".
How can I make this working?
Here is my JS code:
<script type="text/javascript">
var ck_name = /[A-Za-z0-9. ]{3,25}$/;
var ck_email = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form)
{
var name = form.name.value;
var email = form.email.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Name error! .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Email error! .";
}
if (!ck_password.test(password))
{
errors[errors.length] = "Password error!";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Dont use symbols...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
Errors.length never won't be minor of 0. You must use equal (==). This works! :-)
UPDATE
if (errors.length == 0) {
alert('Correct input');
}
That would be before the return true statement and after the if (errors.length > 0).

Password blur event not showing

Im trying to have a blur event for when username and password are to short it says username/password must be x long.
For some reason it only works on my username and I have no clue why
HTML
<body>
<div id="page">
<h1>List King</h1>
<h2>New Account</h2>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" />
<div id="feedback"></div>
<label for="password1">Create a password: </label>
<input type="password" id="password"/>
<div id="feedback"></div>
<input type="submit" value="sign up" />
</form>
</div>
<script src="event-listener.js"></script>
</body>
javascript
function checkUsername() {
var elMsg = document.getElementById('feedback');
if (this.value.length < 5) {
elMsg.textContent = 'Username must be 5 characters or more';
} else {
elMsg.textContent = '';
}
}
var elUsername = document.getElementById('username');
elUsername.addEventListener('blur', checkUsername, false);
function checkPassword() {
var elMsg = document.getElementId('feedback');
if (this.value.length < 6){
elMsg.textContent = 'Password must be 6 characters or more';
} else {
elMsg.textContent = ' ';
}
}
var elPassword = doucment.getElementById('password');
elPassword.addEventListener('blur', checkPassword, false);
Created a plunkr example here< https://plnkr.co/edit/MBkFQSEjbKIAFPDOFUTW?p=preview >. You have few spelling mistakes in your code and used the same id to show the message. I used html5 tags for blur event instead of event listeners.
function checkUsername() {
var usernameLength=document.getElementById('username').value.length;
var elMsg = document.getElementById('feedback1');
if (usernameLength < 5) {
elMsg.textContent = 'Username must be 5 characters or more';
} else {
elMsg.textContent = 'good';
}
}
function checkPassword() {
var elPassword = document.getElementById('password');
var elMsg = document.getElementById('feedback2');
if (elPassword.value.length < 6){
elMsg.textContent = 'Password must be 6 characters or more';
} else {
elMsg.textContent = ' ';
}
}
</head>
<body>
<div id="page">
<h1>List King</h1>
<h2>New Account</h2>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" />
<div id="feedback"></div>
<label for="password1">Create a password: </label>
<input type="password" id="password"/> <div id="feedback1"></div>
<input type="submit" value="sign up" />
</form>
</div>
<script src="event-listener.js"></script>
</body>
</html>
function checkUsername() { // Declare function
var elMsg = document.getElementById('feedback'); // Get feedback element
if (this.value.length < 5) { // If username too short
elMsg.textContent = 'Username must be 5 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear msg
}
}
var elUsername = document.getElementById('username'); // Get username input
// When it loses focus call checkUsername()
elUsername.addEventListener('blur', checkUsername, false);
function CheckPassword() { // Declare function
var elMsg = document.getElementById('feedback1'); // Get feedback element
if (this.value.length < 6) { // If username too short
elMsg.textContent = 'Password must be 6 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear msg
}
}var elPassword = document.getElementById('password'); // Get username input
elPassword.addEventListener('blur', CheckPassword, false);

Categories