Submitting form within a function - javascript

Probably a very easy fix for you JS gurus out there, currently I have a form with some basic validation. If i call it outside of a submit function it works fine, however i need the form to submit once it checks the validation, can anyone help? Also is the correct way to call it by returning true at the bottom of the function?
function submitForm() {
//Form validation, post.
submitBtn.addEventListener("click", function(event) {
event.preventDefault();
//Form fields
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
//Check if values aren't empty, if they're not post form. Else alert the user to complete.
contactName !== '' && contactEmail !== '' && contactPhone !== '' && contactMessage !== '' ?
true :
alert("Please complete form");
})
}
<form action="#" method="post">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input id="submitbtn" type="submit" value="send my message" onsubmit="submitForm()" />
</div>
</form>

Use preventDefault() only if the validation doesn't pass.
document.getElementById('contact-form').addEventListener('submit', function(e) {
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
if (contactName === '' || contactEmail === '' || contactPhone === '' || contactMessage === '') {
e.preventDefault();
alert("Please complete form");
}
});
<form action="#" method="post" id="contact-form">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input type="submit" value="send my message" />
</div>
</form>

Related

Bootstrap form doesn't cancel submission when validation failed

I'm trying to create a form which will send an email to the user on submit.
The thing is that I used Bootstrap's form template and when I submit it with phone and mail wrong values (phone number even empty), the email is sent anyway (with 200 ok) and a success alert is showing.
Here is my HTML code:
<form class="needs-validation" novalidate id="paymentForm">
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Lasr Name</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email</label>
<input type="email" class="form-control" value="" name="email" id="email" placeholder="you#example.com" required>
<div class="invalid-feedback">
please enter a valid mail address
</div>
</div>
<div class="mb-3">
<label for="phone">Phone Number</label>
<input type="tel" class="form-control" value="" name="phone" placeholder="example: 050-1111111" pattern="[0]{1}[5]{1}[0-9]{8}" id="phone" required>
<div class="invalid-feedback">
please provide a valid phone number
</div>
</div>
<div class="mb-3">
<label for="address"> address</label>
<input type="text" class="form-control" name="address" id="address" placeholder="" required>
<div class="invalid-feedback">
please provide your address
</div>
</div>
<hr class="mb-4">
<h4 class="mb-3">payment method</h4>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input id="cash" value="cash" value="cash" name="paymentMethod" type="radio" class="custom-control-input" required checked>
<label class="custom-control-label" for="cash">cash</label>
</div>
<div class="custom-control custom-radio">
<input id="bit" value="bit" value="bit" name="paymentMethod" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="bit">Bit</label>
</div>
</div>
<div class="invalid-feedback">
please choose method
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">continue to checkout</button>
</form>
and here is my js:
(function() {
'use strict'
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation')
Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
var radioValue = $('#paymentForm input:radio:checked').val()
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated')
var orderNumber = generateId();
var cName = $('#firstName').val() + " " + $('#lastName').val()
var cEmail = $('#email').val()
var cPhone = $('#phone').val()
var cAddress = $('#address').val()
var cSumToPay = parseInt(localStorage.getItem("totalPrice"));
var cProducts = JSON.parse(localStorage.getItem("products") || "[]");
cProducts = cProducts.map(Object.values);
cProducts = cProducts.join(' ');
console.log(cProducts);
var templateParams = {
order_number: orderNumber,
customer_name: cName,
products: cProducts,
addres: cAddress,
phone: cPhone,
customer: cEmail,
payment_Methode: radioValue,
customer_sum: cSumToPay
};
emailjs.send('gmail', 'orderconfirmation', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
alert('Yey! Your email was sent :)');
}, function(error) {
console.log('error');
alert(error);
});
event.preventDefault();
}, false)
})
}, false)
}())
I would be thankful if you guys can help me!!!
This section appears to be your only check for validation:
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
However, event.preventDefault() and event.stopPropagation() are not going to prevent the code from falling through to the next section. You can do that by including a return at this point
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
return false;
}
or you can wrap the rest of your code in the else of your conditional
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
// your email handling code
}
Note: your event.preventDefault() is useful to stop the submit button from performing its default behavior of submitting the form and event.stopPropagation() will just keep the event from bubbling up to parent elements (which you likely don't need). See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
In any case, you do not need two event.preventDefault() calls if you place a single one at the top of your event listener, e.g.
form.addEventListener('submit', function(event) {
event.preventDefault();
...

HTML form showing error even after entering correct values

I have a contact form including validations. HTML form shows an error on entering wrong values but after correcting the values and entering appropriate data it continues to show the same error. I am validating the form using pattern attribute in the form.
The code below includes the form and the script which is used for validation.
Here is the part of the document:
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Create Account</h1>
<div>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" pattern='^[a-zA-Z ]*$' autofocus required/>
</div>
<!--<?php if(isset($msg_name)) echo "<script>alert('$msg_name')</script>";?>-->
<div>
<input type="text" name="username" id="username" class="form-control" placeholder="Username" autofocus required />
</div>
<!--<?php if(isset($msg_username)) echo "<script>alert('$msg_username')</script>";?>-->
<div>
<input type="email" name="email" id="email" class="form-control" placeholder="Email" pattern='^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$' autofocus required/>
</div>
<!--<?php if(isset($msg_email)) echo "<script>alert('$msg_email')</script>";?>-->
<div>
<input type="text" name="phone" id="phone" class="form-control" placeholder="PhoneNumber" autofocus required />
</div>
<div>
<input type="password" name="password" id="password1" class="form-control" placeholder="Password" autofocus required />
<input type="checkbox" onclick="signup_pass()">Show Password
</div><br>
<!--<?php if(isset($msg_password)) echo "<script>alert('$msg_password')</script>";?>-->
<div>
<input class="btn btn-default submit" type="submit" name="submit" value="SIGNUP" >
<?php if(isset($error)) echo "<script>alert('$error')</script>";?>
<?php if(isset($message)) echo "<script>alert('$message')</script>";?>
</div>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">Already a member ?
Log in
</p>
<div class="clearfix"></div>
<br />
<div>
<h1> Elegocart!</h1>
<p>©2018 All Rights Reserved.Privacy and Terms</p>
</div>
</div>
</form>
</section>
</div>
</div>
</div>
<script>
function login_pass() {
var x = document.getElementById("password");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
function signup_pass() {
var x = document.getElementById("password1");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
var name = document.getElementById('name');
var username = document.getElementById('username');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var password = document.getElementById('password1');
name.oninvalid = function(event)
{
event.target.setCustomValidity("Name should include only alphabets and white space");
}
username.oninvalid = function(event)
{
event.target.setCustomValidity("a-z, 0-9, underscore, hyphen");
}
email.oninvalid = function(event)
{
event.target.setCustomValidity("Must be of valid email format");
}
phone.oninvalid = function(event)
{
event.target.setCustomValidity("Enter aaa valid phone number");
}
password.oninvalid = function(event)
{
event.target.setCustomValidity("Password : must contain uppercase,lowercase,numbers and special characters , and shouldbe minimum of 8 characters long");
}
</script>
Probably your function is wrong try something like this :
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Unable to validate more than the first entry in a form

I am trying to validate a form using Javascript but as of right now, it is validating the first form entry and ignoring the rest. If I have less than 6 characters, it'll stop the form from submitting. Once I add more characters, it'll act like the form is fine and submit it, even if everything else is wrong.
HTML:
<form class="form-horizontal" onsubmit="return validator(this);">
<div class="form-group">
<label class="control-label col-xs-3" for="userName">Username:</label>
<div class="col-xs-9">
<!-- USERNAME --><input type="text" class="form-control" id="userName" placeholder="Username"maxlength="50">
<p id="userNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="Password">Password:</label>
<div class="col-xs-9">
<!-- PASS1 --><input type="password" class="form-control" id="Password" placeholder="Password"maxlength="50">
<p id="password1Emsm"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="Password2">Re-enter Password:</label>
<div class="col-xs-9">
<!-- PASS2 --><input type="password" class="form-control" id="Password2" placeholder="Re-enter Password"maxlength="50">
<p id="password2Emsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="firstName">First Name:</label>
<div class="col-xs-9">
<!-- FIRSTNAME --><input type="text" class="form-control" id="firstName" placeholder="First Name"maxlength="50">
<p id="firstNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="lastName">Last Name:</label>
<div class="col-xs-9">
<!-- LASTNAME --><input type="text" class="form-control" id="lastName" placeholder="Last Name"maxlength="50">
<p id="lastNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="zipCode">Zip Code:</label>
<div class="col-xs-9">
<!-- ZIPCODE --><input type="text" class="form-control" id="zipCode" placeholder="Zip Code" maxlength="10">
<p id="zipCodeEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="phoneNumber">Phone Number:</label>
<div class="col-xs-9">
<input type="tel" class="form-control" id="phoneNumber" placeholder="Phone Number"maxlength="12">
<p id="phoneNumberEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="inputEmail">Email Address:</label>
<div class="col-xs-9">
<!-- EMAILADDRESS --><input type="email" class="form-control" id="inputEmail" placeholder="email#address.com"maxlength="100">
<p id="emailEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group"><!-- BUTTONS -->
<div class="col-xs-offset-3 col-xs-9">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</form>
JS:
function validator(form) {
var userName = document.getElementById("userName");
var password = document.getElementById("Password");
var password2 = document.getElementById("Password2");
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var email = document.getElementById("inputEmail");
var passwordFormat = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
var emailFormat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (userName.value.length < 6) {
document.getElementById("userNameEmsg").innerHTML = "Must have at least 6 characters.";
return false;
}
else if (password.value.length == 0) {
document.getElementById("password1Emsg").innerHTML = "Please enter a password.";
return false;
}
else if (!password.value.match(passwordFormat)) {
document.getElementById("password1Emsg").innerHTML = "Enter correct password format.";
return false;
}
else if (password.value != password2.value) {
document.getElementById("password2Emsg").innerHTML = "Passwords do not match.";
return false;
}
else if (email.value.length < 1) {
document.getElementById("emailEmsg").innerHTML = "Please enter an email.";
return false;
}
else if (!email.value.match(emailFormat)) {
document.getElementById("emailEmsg").innerHTML = "Enter correct email format.";
return false;
}
else {
return true;
}
}
I have removed all the elses and have removed the return statement at the bottom and it made no difference to how it funtioned.
Remove all the else if clasues, replace them by pure if and remove the return statement.
Now your code at least, will run through and display all error messages, instead of only the first one.
Now you will need a flag, that signifies, that your form is invalid and disables the Submit button:
function validator(form) {
var userName = document.getElementById("userName");
var password = document.getElementById("Password");
var isFormValid = true;
if (userName.value.length < 6) {
document.getElementById("userNameEmsg").innerHTML = "Must have at least 6 characters.";
isForValid = false;
}
if (password.value.length == 0) {
document.getElementById("password1Emsg").innerHTML = "Please enter a password.";
isForValid = false;
}
/**check if form is Vald **/
if(!isFormValid){
//disable submit button
}
}
But if you can avoid it: use as much, of the built-in function of html as possible. There is no reason you could not just use
<input type="email" id="emailField" required />
and then call document.getElementById('emailField').checkValidity();

convert JQuery code to Pure Javascript

I'm trying to rewrite the following JQuery to Pure Javascript.
I don't know why the code isn't working, but it isn't working. I'm guessing I'm doing wrong with the use of "focusing". Would anybody help me please?
JQuery(working)
$('.form-group input').on('focus blur', function (e) {
$(this).parents('.form-group').toggleClass('active', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
This is what I have so far(not working).
const inputs = document.querySelectorAll(".form-group input")
Array.from(inputs).forEach(input => {
input.addEventListener("focusin", (e) => {
const t = e.target as HTMLInputElement
let formgroup = t.parentElement
if(t.value.length > 0 ){
formgroup.classList.toggle("onblur")
}
})
})
Here is the html tag.
<form action="#" id="login-form">
<div class="form-group">
<label class="label-control">
<span class="label-text">Email</span>
</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label class="label-control">
<span class="label-text">Password</span>
</label>
<input type="password" name="password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn" />
</form>
A couple of issues in regards to the jQuery code.
The class is named active and you are using onblur. The jquery code runs on both focus and blur.
const inputs = document.querySelectorAll(".form-group input");
const focusBlurHandler = (e) => {
const t = e.target;
let formgroup = t.parentElement;
if(t.value.length > 0 ){
formgroup.classList.toggle("active");
}
};
Array.from(inputs).forEach(input => {
input.addEventListener("focusin", focusBlurHandler);
input.addEventListener("focusout", focusBlurHandler);
});
.active{background:lightgreen}
<form action="#" id="login-form">
<div class="form-group">
<label class="label-control">
<span class="label-text">Email</span>
</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label class="label-control">
<span class="label-text">Password</span>
</label>
<input type="password" name="password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn" />
</form>

Form Validation with jQuery - Weird Redirect

Alright, so I'm trying to do form validation with jQuery. Not sure why but when you click submit it redirects you to the page you're at already.
The forms action is blank and I included the javascript file in the header.
I will put the code below. Let me know if you see whats wrong. I want it to validate with jQuery then send you to a php file with those values in the method POST.
Register.js:
$(document).ready(function() {
$('button[name=regsubmit]').click(function(){
var fname = $('input[name=regfirstname');
var lname = $('input[name=reglastnaame');
var email = $('input[name=regemail');
var password = $('input[name=regpassword');
var repeatpassword = $('input[name=regrepeatpassword');
var username = $('input[name=regusername');
var atpos = email.indexOf("#");
var dotpos = email.indexOf(".");
if (fname==null || fname=="")
{
alert('First name must be filled out!');
return false;
}
if (lname==null || lname=="")
{
alert('Last name must be filled out!');
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert('Not a valid e-mail address!');
return false;
}
if (username==null || username=="")
{
alert("Username field must be filled out!");
return false;
}
if (password==null || password=="")
{
alert("Subject field must be filled out!");
return false;
}
if (repeatpassword==null || repeatpassword=="")
{
alert("Repeat password field must be filled out!");
return false;
}
if (password != repeatpassword)
{
alert("The passwords do not match!");
return false;
}
else
{
location.href="register.php";
}
});
});
Form:
<form name="register" method="POST">
<fieldset>
<div class="form-container row-fluid">
<div class="span6">
<div class="control-group">
<label class="control-label" for="regfirstname">First Name</label>
<div class="controls">
<input id="regfirstname" tabindex="1" name="regfirstname" type="text" placeholder="First Name" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regusername">Username</label>
<div class="controls">
<input id="regusername" tabindex="3" name="regusername" type="text" placeholder="Username" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regpassword">Password</label>
<div class="controls">
<input id="regpassword" tabindex="5" name="regpassword" type="password" placeholder="Password" class="input-large">
</div>
</div>
<div class="controls">
<button id="regsubmit" tabindex="7" name="regsubmit" class="button background-asbestos">Submit</button>
</div>
</div><!-- .span6 -->
<div class="span6">
<div class="control-group">
<label class="control-label" for="reglastname">Lastname</label>
<div class="controls">
<input id="reglastname" tabindex="2" name="reglastname" type="text" placeholder="Lastname" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regemail">Email</label>
<div class="controls">
<input id="regemail" name="regemail" tabindex="4" type="text" placeholder="example#example.com" class="input-large"</td>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regrepeatpassword">Repeat Password</label>
<div class="controls">
<input id="regrepeatpassword" tabindex="6" name="regrepeatpassword" type="password" placeholder="Repeat Password" class="input-large" required>
</div>
</div>
<!-- .span6 -->
<!-- span6 -->
</div><!-- .row-fluid -->
</fieldset>
</form>
Alright your JS and HTML is a big mess of stuff, so I won't recreate it all, but basics:
Give your form an ID:
<form id="SomeForm" name="register" method="POST">
Then prevent default action, and submit if passes:
// reference the button by the ID you gave it
$('#regsubmit').click(function(e){
// stop original submission
e.preventDefault();
// all your checking stuff here, but if true, then:
document.getElementById('SomeForm').submit();
});
This ensures that you are referencing the button correctly, preventing submission correctly, and submitting only if valid.
prevent default action on submit
$('button[name=regsubmit]').click(function(e)
{
e.preventDefault();
//your code below
}

Categories

Resources