How to not submit form if there are validation fields outstanding? - javascript

I have a page that contains some required fields. An attachment file field, some text boxes including checking email valid and matching and making sure not empty, and selecting a checkbox to ensure user acknowledges terms and conditions.
The problem I have is, if I don't fill out the form and click 'Buy now', it does perform a validation, but it then redirects the user to checkout. How can we get it so that the submit button does not redirect, if there are validation present on the form? I use required in html and some javascript for email validation.
HTML FROM
<form id="tcform">
<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> £40
<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 10 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>
Javascript
<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() {
var stripe = Stripe('pk_test_xxxxxxxxxxxxxx');
var checkoutButton = document.getElementById('checkout-button-sku_xxx');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
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 + '//www.xxx.com/services/cv-rewrite',
cancelUrl: window.location.protocol + '//www.xxx.com/services/cv-rewrite',
})
.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;
}
});
});
})();
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;
}
$(".buynow").on("click", validate);
window.onload = function(){
var label = document.getElementsByClassName('close');
for (var i = 0; i<label.length; i++) {
label[i].onclick = function () {
var el = (this.parentNode);
el.parentNode.removeChild(el);
};
}
};
</script>

You should call your validate method before the stripe redirect and you should also check the forms default validation (form.checkValidity()) for things that you do not manually check in your validate method.
checkoutButton.addEventListener('click', function(event) {
event.preventDefault();
// When the customer clicks on the button, redirect
// them to Checkout if validations pass.
const isFormValid = checkoutButton.form.checkValidity() && validate();
if (!isFormValid) return; // or show message or whatever else you want
stripe.redirectToCheckout({
items: [{
sku: 'sku_xxx',
quantity: 1
}],
...

Related

ValidateForm How to validate and show text when submit button was clicked in JavaScript

I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>

Submit button clearing out form, and not displaying anything

I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)

Submitting an HTML form to a PHP file with JS validation

I'm sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script,
The same form is validated with JavaScript functions.
Each of the two works as expected separately,
but when used together - <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)"> -
only the validation function works, and the page doesn't get redirected to the PHP file.
When removing the JS (leaving only <form method="POST" action="myPHPFile.php">) - the data from the form is submitted properly and the page is redirected to the PHP file as expected.
I need to have some JS function to stop if the input is invalid,
and another to continue and send the input data to the PHP file if it's valid.
Example code:
function isInputChars(evt) {
let ch = String.fromCharCode(evt.which);
if (!(/[a-z,A-Z,-]/.test(ch))) {
alert("Please only enter only characters")
evt.preventDefault();
}
}
function validateForm(event) {
event.preventDefault();
var validateFormInputs = [];
var inputLength;
StringInput = document.getElementById("city");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("City: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
StringInput = document.getElementById("street");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("Street: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
var x;
for (var i = 0; i < 2; i++) {
if (validateFormInputs[i] === false) {
x = false;
break;
} else {
x = true;
}
}
if (x == true) {
console.log("Data is sent to DB")
someFunctionToContinueSendingTheData();
} else {
console.log("Data is INVALID")
someFunctionToStop();
}
}
<form name="myForm" method="POST" action="sendItem.php" onsubmit="validateForm(event)">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish">
</form>
I'd be happy for some help with:
How to redirect the input data to the PHP file (without removing the JS validation)
How to implement the JS functions to send the data to the PHP/cancel.
Thank you!
Instead of the button being a submit button just have it be a regular button that calls your javascript function. Then, do all of your validation in the function... at the end, you can have a conditional statement which checks if all conditions are met. If they are, then submit the form. (Assign an id to your form)
Check out this pseudo-code
let me know if this works or you need further instruction
function validateForm(){
... conditional logic ...
if(all conditions met){
document.getElementById('form-id').submit();
}
}
It simple you need to use AJAX to Send a Request To your PHP Server
i will show you a simple example
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object.
you can use POST or GET
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no size limitations).
Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
<script type="text/javascript">
function myFunction() {
var name = document.getElementById("name").value; // get the name
var email = document.getElementById("email").value; // get the mail
var xhttp = new XMLHttpRequest();
var url = 'test.php'; // your php file
xhttp.open('POST', url, true); // method =POST
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// send data
var params="name="+name+"&email="+email;
xhttp.onreadystatechange = function() {
//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.send(params);
}
</script>
<form name="myform" method="POST">
<input type="text" name="name" id="name">
<input type="mail" name="email" id="email">
<input class="btn btn-success" type="button" name="conf" value="OK" onclick="myFunction()">
<input class="btn btn-danger" type="reset" name="cancel" value="cancel">
</form>
You need some changes in your code:
First: you can set validation function on the submit input.
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick = "return validateForm();">
Second: you must return true or false at validation function.
if (x == true) {
console.log("Data is sent to DB");
return true; //input data is valid!
someFunctionToContinueSendingTheDate();
} else {
console.log("Data is INVALID")
someFunctionToStop();
return false; //input data is invalid!
}
Finally: here you are:
HTML:
<form name="myForm" method="POST" action="sendItem.php">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick="return validateForm();"></form>
JS:
<script>
function isInputChars(evt) {
let ch = String.fromCharCode(evt.which);
if (!(/[a-z,A-Z,-]/.test(ch))) {
alert("Please only enter only characters")
evt.preventDefault();
}
}
function validateForm() {
var validateFormInputs = [];
var inputLength;
StringInput = document.getElementById("city");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("City: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
StringInput = document.getElementById("street");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("Street: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
var x;
for (var i = 0; i < 2; i++) {
if (validateFormInputs[i] === false) {
x = false;
break;
} else {
x = true;
}
}
if (x == true) {
console.log("Data is sent to DB");
return true;
someFunctionToContinueSendingTheDate();
} else {
console.log("Data is INVALID")
someFunctionToStop();
return false;
}
}</script>

Built a login form script but it's not working using JavaScript

I am trying to build a login.js script that listens for the login form submit event. When I try to run my code, it's not logging in or working properly
I' working with JavaScript, which is requested to use. I built the login form in HTML and have worked on the login function within JavaScript. It can;t be inline JavaScript, it has to be a separate script from HTML.
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["adrian#tissue.com",
"dduzen1#live.spcollege.edu",
"deannaduzen#gmail.com"
]
var passwordArray = ["welcome1", "w3lc0m3", "ch1c#g0"]
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Login is successful");
window.location = "index.html";
return false;
}
var again = "tries";
if (count == 1) {
again = "try"
}
if (count >= 1) {
alert("Wrong username or password")
count--;
} else {
alert("Incorrect username or password, you are now blocked");
document.login.username.value = "You are now blocked";
document.login.password.value = "You are now blocked";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
<!-- start of login form -->
<div class="login-page">
<div class="form">
<form class="register-form" onsubmit="return validate() ;" method="post">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<input type="text" placeholder="email id" />
<button>Create</button>
<p class="message">Already registered? Login
</p>
</form>
<form class="login-form">
<input type="text" placeholder="username" />
<input type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
</div>
</div>
It needs to allow the three login information I put into the code to log into the site. When logging in, it blinks as if it's doing something, but isn't going anywhere nor does it show that the person is logged in.
You are not validating correctly with the return sentence, also your onsubmit attribute was in the register form.
Use name attribute on forms
This will help you to identify your forms and inputs easily with JavaScript, otherwise you might have problems identifying which input is which in larger forms.
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>
With this applied to your login form, you can reference it by doing document.login.
Take advantage over native HTML events in JavaScript
The way you are retrieving the username and password is a lot complex that it should, you can add an event listener in JavaScript and handle everything there:
const loginForm = document.login;
loginForm.addEventListener("submit", validate);
This will call validate every time the form is submitted. Also, it sends the event as a parameter, so you can receive it like this in your function:
function validate(event) {
event.preventDefault(); // Stop form redirection
let user = event.target.user.value,
pass = event.target.pass.value;
// REST OF THE CODE ...
}
This is easier since we added name attributes to the inputs, so we can identify them by user and pass.
Validation
NOTE: I do not recommend validating username:password data directly in the browser, since this is a big vulnerability and must be validated server-side.
You can simplify this validation by binding the username with its password in an object, instead of creating two arrays:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
And then, having the inputs value saved in user and pass variables, you can do:
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
//WRONG LOGIN CREDENTIALS
attempts--;
validateAttempts();
}
With the purpose of not having a lot of code in sight, you should create another function that its only job is to validate if you should block the user or not.
The result
I should mention that this will only work to validate the user form, if you need to save a session and keep an user logged in, you must use a server-side language.
I leave you a snippet with all of this changes working, see it for yourself:
const accounts = {
"adrian#tissue.com": "welcome1",
"dduzen1#live.spcollege.edu": "w3lc0m3",
"deannaduzen#gmail.com": "ch1c#g0"
};
const loginForm = document.login;
let attempts = 3;
loginForm.addEventListener("submit", validate);
function validate(event) {
event.preventDefault();
let user = event.target.user.value,
pass = event.target.pass.value;
if (accounts[user] == pass) {
//SUCCESSFUL LOGIN
console.log('Correct. Logged in!');
} else {
console.log('Wrong username or password.');
attempts--;
validateAttempts()
}
}
function validateAttempts() {
if (attempts <= 0) {
console.log("You are now blocked");
loginForm.user.value = "You are now blocked";
loginForm.pass.value = "You are now blocked";
loginForm.user.disabled = true;
loginForm.pass.disabled = true;
}
}
<form name="login" class="login-form">
<input name="user" type="text" placeholder="username" />
<input name="pass" type="text" placeholder="password" />
<button>login</button>
<p class="message">Not registered? Register
</p>
</form>

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

Categories