Trying to fix email validation for school project - javascript

Hey so uh I have a project due in a few days which requires us to make a contact page where someone can enter a name, email address, subject and message. We need to create javascript to make sure all fields are filled in and that the email is valid.
I have written the HTML for the form, as well as the javascript but I have 2 problems:
No error message displays when no message is entered in the memo field
The email field will not accept a valid email
I have tried to change the ID tag for the email but it automatically allows me to submit straight away without entering any data, I'm quite stuck.
Yes, they are both in two separate documents.
Note: I have not included all the code for the contact page, just the relevant form.
Thank you so much
Here are the images of my code:
HTML for contact page:
Javascript for Contact page:
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['emailaddress'].value;
var emailpattern = /\S+#\S+\.\S+/;
var subject = document.forms["contact"]["subject"].value;
var textarea = document.forms["contact"]["memo"].value;
console.log(name, email, subject, textarea);
if(name == ""){
document.getElementById('namemessage').innerHTML = "PLEASE enter a name";
isValid = false;
} else {
document.getElementById('namemessage').style.display = "none";
}
if(!emailpattern.test(emailaddress)){
document.getElementById('emailmessage').innerHTML = "PLEASE enter a valid email";
isValid = false;
}
else {
document.getElementById('emailmessage').style.display = "none";
}
if(subject == ""){
document.getElementById('subjectmessage').innerHTML = "PLEASE enter a subject";
isValid = false;
} else {
document.getElementById('subjectmessage').style.display = "none";
}
if(memo == ""){
document.getElementById('memomessage').innerHTML = "PLEASE enter your request";
isValid = false;
} else {
document.getElementById('memomessage').style.display = "none";
}
return isValid;
}
<main><form action="thankyou.html" name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name">
<p id="namemessage"></p><br><br>
<label for="emailaddress">Email Address:</label>
<input type="text" id="emailaddress">
<p id="emailmessage"></p><br><br>
<label for="subject">Subject:</label>
<input type="text" id="subject"><p id="subjectmessage">
</p><br><br>
<label for=memo>Message:</label><br><br>
<textarea id="memo" placeholder = "please type your message here.">
</textarea>
<br><p id="memomessage"></p><br><br>
<input type="submit" value="Submit">
</form>
</main>

No error message displays when no message is entered in the memo field
Because you have:
var textarea = document.forms["contact"]["memo"].value;
...
if (memo == "") {
Change textarea to memo.
The email field will not accept a valid email
Because you have:
var email = document.forms['contact']['emailaddress'].value;
...
if (!emailpattern.test(emailaddress)) {
Change emailaddress to email.
Fix those issues and it "works".

Related

Form Validation: messages not displaying when all input fields are left empty

So I am practicing Javascript and right now I am trying to implement form validation.
One of the issues I am having is that when I click on the button when all of the input fields are empty, the first one (Full Name) only highlights and displays a message (Please checkout snippet). I was wondering is that how it works - can only one message be displayed at a time or is there a way to get all of the input fields to change color and display messages for each empty field?
function validateForm(e) {
const eName = document.getElementById("FullName");
const eMail = document.getElementById("Email");
const ePhone = document.getElementById("PhoneNumber");
const ePass = document.getElementById("Password");
const eCnfmPass = document.getElementById("ConfirmPassword");
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
const fullNameText = "Oops, please fill out your name";
const emailText = "Please enter a valid email";
const phoneText = "Please enter a valid phone number";
const passText = "Please enter a valid password";
const confirmText = "Please confirm your password";
//Name input validation - If input is left empty
if (eName.value === "") {
e.preventDefault();
document.getElementById("FullName").style.borderColor = "red";
document.getElementById("FullNameLabel").innerHTML = fullNameText;
document.getElementById("FullNameLabel").style.color = "red";
return false;
}
//Email input validation - If input is left empty
if (eMail.value === "") {
e.preventDefault();
document.getElementById("Email").style.borderColor = "red";
document.getElementById("EmailLabel").innerHTML = emailText;
document.getElementById("EmailLabel").style.color = "red";
return false;
}
//Phone number input validation - If input is left empty
if (ePhone.value === "") {
e.preventDefault();
document.getElementById("PhoneNumber").style.borderColor = "red";
document.getElementById("PhoneNumberLabel").innerHTML = phoneText;
document.getElementById("PhoneNumberLabel").style.color = "red";
return false;
}
//Phone number input validation - checks to see if there is a missing number or character that is not a number
if (ePhone.value.match(phoneno)) {
return true;
} else {
alert("Please check your phone number and enter it again")
// document.getElementById("PhoneNumber").style.borderColor = "red";
// document.getElementById("PhoneNumberLabel").innerHTML = phoneText;
// document.getElementById("PhoneNumberLabel").style.color = "red";
return false;
}
//Password input validation - If input is left empty
if (ePass.value === "") {
e.preventDefault();
document.getElementById("Password").style.borderColor = "red";
document.getElementById("PasswordLabel").innerHTML = passText;
document.getElementById("PasswordLabel").style.color = "red";
return false;
}
//Confirm password input validation - If input is left empty
if (eCnfmPass.value === "") {
e.preventDefault();
document.getElementById("ConfirmPassword").style.borderColor = "red";
document.getElementById("ConfirmPswdLabel").innerHTML = confirmText;
document.getElementById("ConfirmPswdLabel").style.color = "red";
}
}
//Checks to make sure that both password and confirm passwords match
var passConfirm = function() {
if (document.getElementById("Password").value ==
document.getElementById("ConfirmPassword").value) {
document.getElementById("Message").style.color = "green";
document.getElementById("Message").style.fontWeight = "Heavy";
document.getElementById("Message").innerHTML = "Passwords match!"
} else {
document.getElementById("Message").style.color = "red";
document.getElementById("Message").style.fontWeight = "Heavy";
document.getElementById("Message").innerHTML = "Passwords do NOT match!"
}
}
<div class="container">
<form class="form" onsubmit="validateForm(event)">
<div>
<label id="FullNameLabel">Full Name</label></br>
<input type="text" placeholder="John Doe" id="FullName" />
</div>
<div>
<label id="EmailLabel">Email</label></br>
<input type="text" placeholder="johndoe#email.com" id="Email" />
</div>
<div>
<label id="PhoneNumberLabel">Phone Number</label></br>
<input type="text" placeholder="(123) 456-7890" id="PhoneNumber" />
</div>
<div>
<label id="PasswordLabel">Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onkeyup='passConfirm();' />
</div>
<div>
<label id="ConfirmPswdLabel">Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onkeyup='passConfirm();' />
</div>
<span id="Message"></span>
<button type="submit" value="submit">Sign Me Up!</button>
</form>
</div>
You have too much javascript code, you can simplify that, alot.
to check if any of the inputs are empty, you can first store all the inputs in a variable like that:
let inputs = document.querySelectorAll('.form input') //This will make a Nodelist array of all the inputs inside the form.
let labels = document.querySelectorAll('.form label') //This will make a Nodelist array of the label tags inside the form
after that you can loop through the inputs array to find if any of the inputs are empty:
for (let i = 0; i < inputs.length; i++) {
if (inputs.value.length == 0) {
inputs[i].style.borderColor = 'red'
label[i].textContent = 'Please fill in this input'
}
}
Require your inputs. Why go through all that trouble making sure they're filled out?
<input required>

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

JavaScript Validation error message is not disappearing after I click submit

The code below validates a form with two fields. When I click the submit button without any data the error messages would show which is working fine but if I input data after and click submit button the error message doesn't disappear.
<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>
<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>
The other answer is right, but here is some code to back it up with. Notice that the innerHTML of both activityName and reporter get (re)set back to empty before the validation occurs:
function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}
var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}
return valid;
}
Your problem is you never "unvalidate" the form a.k.a. remove the previous validation errors. Before you return from validation, if there were no errors, just revert your validation checks. This will ensure it will "clean" your interface if nothing is wrong.

How to make email id in a form optional in JavaScript

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">

JavaScript Form HTML

Evening,
I have to validate a HTML form by pushing it through a Javascript function to make sure no illegal characters are in it. How would I do it for Customer Number and separately for Password but in the same form as they both need to go through to login.jsp
<form onsubmit="return validateNum(this)" action="login.jsp" >
Customer Number: <input type="text" name="customerNumber"/><br/>
Password: <input type="password" name="passphrase"/><br/>
<input type="submit" />
</form>
I am aware that it is completely pointless doing it through Javascript as it can be disabled via the browser and a better way would be through the HTML form its self but that is the parameter that has been set.
I have
function validateNum(fld)
{
var error = "";
var illegalNum = /[\(\)\<\>\,\;\:\\\"\[\]]/[a-z][A-Z];
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "The required field has not been filled in.\n"
}
else if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a Customer Number.\n";
}
else {
fld.style.background = 'White';
}
}
It's half finished as I realized if I put illegal characters A-Z then the password wont work .

Categories

Resources