form validation and submission not working as expected - javascript

I am having an issue with my validation and form submission. Even though it can check the required fields via HTML 5 after pressing the 'Buy Now' button, there are two issues that occur:
1: I can submit the form even though the email field is empty and the javascript validation reflects that. What should happen is that a valid email and matching confirm email must be entered along with the other fields entered for the form is to successfully validated.
2: It does not take the user to the stripe checkout page. The code I have taken from their codebase. If I remove all my validation and click 'Buy Now', it works but not with validation.
<p>
<b>Attach your CV:</b> (.doc, .docx, .pdf, .txt, .rtf)
</p>
<input type="file" id="uploadCV" required/>
<br/>
<br/>
<div class="formcontainer">
<label for="email"><b>Email:</b></label>
<input type="input" id="email" name="email" />
<p id="resultEmail"></p>
<label for="email"><b>Confirm Email:</b></label>
<input type="input" id="confirmEmail" name="confirmEmail" />
<p id="resultConfirmEmail"></p>
<label for="job"><b>Desired Job Position:</b></label>
<input type="input" id="job" name="job" required/>
</div>
<br/>
<p><b>Quantity:</b> 1</p>
<b class="price">Price:</b> £20
<button type="submit" class="btn btn-default buynow" id="checkout-button-sku_xxx" role="link">
Buy Now
</button>
<p class="tcparagraph"><i style="font-size:small">Expected Completion Time: Within 7 working days</i></p>
<p class="tcparagraph">
<input id="field_terms" type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
</form>
</div>
</div>
</div>
<!-----------Footer------->
<section id="footer">
<div>
Terms And Condition
Privacy Policy
Cookies Policy
</div>
<p>METIS © 2020 All Rights Reserved</p>
</section>
<script>
var file = document.getElementById('uploadCV');
file.onchange = function(e) {
var ext = this.value.match(/\.([^\.]+)$/)[1];
switch (ext) {
case 'doc':
case 'docx':
case 'pdf':
case 'txt':
case 'rtf':
break;
default:
alert('Please upload a file that matches any of these file types: .doc, .docx, .pdf, .txt, .rtf');
this.value = '';
}
};
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var $result = $("#resultEmail");
var $confirmResult = $("#resultConfirmEmail");
var email = $("#email").val();
var confirmEmail = $("#confirmEmail").val();
$result.text("");
if (validateEmail(email)) {
if (email == confirmEmail) {
$confirmResult.text("");
return true;
} else {
$confirmResult.text("Your email and confirm email do not match");
$confirmResult.css("color", "red");
}
} else {
$result.text("You have not provided a valid email");
$result.css("color", "red");
}
return false;
}
(function() {
var stripe = Stripe('pk_test_xxx');
var checkoutButton = document.getElementById('checkout-button-sku_xxx');
checkoutButton.addEventListener('click', function() {
// When the customer clicks on the button, redirect
// them to Checkout.
const isFormValid = checkoutButton.form.checkValidity();
// if (!isFormValid) return true;
if(validate()==true && isFormValid==true){
stripe.redirectToCheckout({
items: [{
sku: 'sku_xxx',
quantity: 1
}],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//metis-online.com/services/service-CVREW211392-order-confirmation.php?email=' + $("#email").val(),
cancelUrl: window.location.protocol + '//metis-online.com/order-cancelled',
})
.then(function(result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
}
});
})();
</script>

Related

Want to only accept certain email address in html form

I'm creating a form where only a certain email address is accepted. If the wrong address is used, then a message should appear.
I want to use something like ".pattern != email" within my script, however I understand this attribute can only be used within input. I've tried to use .match as well without any success.
This is a snippet of the form:
<form onsubmit="return validation()">
<label for="email"> <b> Email: </b> </label>
<input type="email" name="email" id="emailinput" placeholder="Please enter email"
pattern=".+#gmail.com"> <span id="message"></span>
</form>
The relevant script:
<script>
funcion validation() {
if (document.getElementById("emailinput").pattern != ".+#gmail.com") {
document.getElementById("message").innerHTML
= "<em> Must be a gmail '#gmail.com' account </em>";
return false;
else
return true;}
</script>
#(gmail.com) will match #gmail.com specifically...
# matches the # symbol
Something like [a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+[\S] for the portion before your # section may work...
[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+[\S]#(gmail.com)
Run your email through a function and return regex.test(email), this will return a Boolean value that can be used in a conditional.
let email = document.getElementById('email');
let b = document.getElementById('b');
const emailIsValid = (email) => {
return /[\S]+#(gmail.com)/.test(email)
}
b.addEventListener('click', function() {
emailIsValid(email.value)?
console.log(emailIsValid(email.value)):
console.log(emailIsValid(email.value) + ': ' + email.value + ' is not valid gmail address!');
})
Enter an email: <input id="email"> <button id="b">Test It</button>

Trying to fix email validation for school project

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".

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.

How to change errorMess value based on a condition in form-validator jquery plugin

I am trying to validate a form using jquery form validator plugin. I want to display custom messages like if the email is not given then it should display email address is required, if email value is not a valid one then it should display invalid email address. But in both cases, it is giving me the same default message like 'You have not given a correct e-mail address'. I tried to like this
<form action="" id="registration-form">
<p>E-mail
<input name="email" id="email" data-validation="email" >
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
The script is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.20/jquery.form-validator.min.js"></script>
$.validate({
onElementValidate : function(valid, $el, $form, errorMess) {
if ($el.attr('name') == 'email') {
alert('Input ' +$el.attr('name')+ ' is ' + ( valid ? 'VALID':'NOT VALID') );
var value = $('#email').val();
if (value) {
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (! filter.test(value)) {
alert('invalid');
errorMess = 'invalid email';
}
} else {
alert('no mail');
errorMess = 'no email';
}
}
alert('errorMess :: ' + errorMess);
$('.help-block form-error').html(errorMess);
},
borderColorOnError: '#b94a48',
errorMessagePosition : 'inline',
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
It is pretty simple, adding multiple values in data-validation will actually done the magic.
<input name="email" id="email" data-validation="required, email" >

Validating form using HTML and JavaScript - Checking form input matches a value in an array

I have a simple web form which accepts a user email and password for log in.
I want to check the users email and password match up with what is stored in an external javascript file and if the combination matches then proceed to the index.html page.
My array is declared in my router file as follows:
var USERS = { users: [] };
function User(type, useremail, password) {
this.type = type;
this.useremail = useremail;
this.password = password;
}
var Bob = new User("rep", "bob#bob.com", "qwerty");
USERS.users.push(Bob);
var Helen = new User("rep", "helen#helen.com", "test");
USERS.users.push(Helen);
var Dominic = new User("customer", "dom#dom.com", "1234");
USERS.users.push(Dominic);
var James = new User("grower", "james#james.com", "pass1");
USERS.users.push(James);
My html form is as follows:
<div id="loginform">
<form id ="login" name="login" method="post" accept-charset="utf-8" onsubmit="return verify();">
<h1> </h1>
<label>
<span>Email Address:</span>
<input id="email" type="email" name="email" placeholder="Enter a valid email address" required />
</label>
<br>
<label>
<span>Password:</span>
<input id="password" type="password" name="password" placeholder="Password" required />
</label>
<br> <br>
<label id="reset">Click here to reset your password
</label>
<br>
<label>
<span> </span>
<input id="submit_button" type="submit" value="Login" />
</label>
<!-- <input type="submit" value="Login" onsubmit = "verify()"> --><!-- <input type="submit" name="submit" value="Send"> -->
</form> <!-- End of log in form -->
</div>
My attempt at checking if the user email and password combo match:
function verify() {
validUser = false;
for (var x in USERS.users){
//console.log(USERS.users[x].userid);
if (query.useremail === USERS.users[x].useremail
&& query.password === USERS.users[x].password)
{
validUser = true;
break;
} // end of if
}// end of for
console.log(validUser);
if (validUser === true){
console.log("logged in");
res.render('index.html');
}
}
Just in case you need to see it, a section in my router where I feedback the log in page on request:
app.get('/views/login.html', function (req, res) {
res.render('../views/login.html');
//console.log("Log in page displayed");
});
app.post('/views/login.html', function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query);
console.log("Username: " + query.useremail);
console.log("Password: " + query.password);
});
I've confused myself with all the different codes and files ... How do I go about verifying that the user can log in?
Where do I put my verify() function? I currently have it within the router file below the user data - but I want to use it within HTML so I was considering putting into tags there...?
I supose that you use Javascript as server with NodeJS, then you need to create a route for <form id ="login" action="path"... wiht method POST. In the server:
app.post([path type on action], function(req, res) {
verify();
}
You catch input values: req.body.[attr name of input]. For example, for email:
var email = req.body.email;

Categories

Resources