User Registration - Incorrect Logic - javascript

I'm having multiple issues with my code. I have wrote a user registration form with validation, however I need help on what I would write for it to be saved in the database and if I'm missing anything. As of right now, it is not working. When I click register, it just refreshes the page.
I appreciate any help, thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<SCRIPT language="JavaScript">
function validateRegistrationForm(){
if(!validateEmailField()) // Invalid email format
return false;
if(!validatePasswordField()) // Invalid password length
return false;
if(validateUserNameField()) // invalide characters in email
return false;
}
function validateEmailField(){
var x=document.getElementById("email").value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
errorPopup("Not a valid e-mail address");
return false;
}
if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored.
return true;
return isEmailUnique(); // return true if the email is unique
}
</script>
</head>
<body class="nobg loginPage">
<header>
</header>
<div id="content">
<div class="ic"></div>
<div class="inner">
<div class="container_12">
<div class="wrapper">
<div class="grid_12">
</div>
</div>
<div class="wrapper">
<div class="grid_12">
<h2 class="h-pad1">Open an Account with Us</h2>
<form action="" id="validate" class="form" method="POST">
<fieldset>
<div class="formRow">
<label for="login">Username:</label>
<div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Password:</label>
<div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Repeat Password:</label>
<div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Email:</label>
<div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div>
<div class="clear"></div>
</div>
<div class="formRow5">
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6Lfz39kSAAAAABY7fpEs0x1ZzvcFSP-gClbe8XYb"></script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6Lfz39kSAAAAABY7fpEs0x1ZzvcFSP-gClbe8XYb" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript> </div>
<div class="loginControl">
<input type="submit" value="Register" class="dblueB logMeIn" name="registerBtn"/>
<div class="clear"></div>
</div>
</fieldset>
</form>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<footer>
</div>
</footer>
</body>
</html>

As far as I can tell - you don't have anything linking the submission of the form, to the validation code you've written. Is your validateRegistrationForm() function even being called when you submit the form?
As for your function - you'll want to return true if the form elements are valid, and false if they are not. returning false will cancel submission of the form.

In most cases, you can't use JavaScript to write to a database as JS is client-side code and the database tends to be on a server. In that case you'll need to use a server-side language to do so (like .NET, PHP, Java, etc.). You might be able to get a more detailed answer if you can say what database you want to write to and what server language you are using (if you are using any already).

Before you click the register button, there's a javascript error...
Line 14 column 1: "Uncaught SyntaxError: Unexpected token . "

Related

Bootstrap JavaScript for disabling form submissions if there are invalid fields & the rest form is not working as intended

I am using the bootstrap version 4. Index.php includes the below contact form. I want users to see the validation messages when they click submit to draw their attention to the required fields they have missed. For example, when a user hits submit without filling any field, the user sees the below, which is the behavior I want to achieve, and I currently have:
[please note that to save space in this post, all images can be shown by clicking on run code snippet]
<img src="https://i.stack.imgur.com/h1KwJ.png" width="50%" height="50%" />
The contact form: Index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Contact form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class ="container">
<div class="col-lg-6 push-lg-3">
<h1> Contact us</h1>
<p>Fill out the below form to contact us</p>
<form id="contactForm" class="contact-form needs-validation" action="form.php" method="POST" novalidate>
<div class="contact-form-success alert alert-success d-none mt-4" id="contactSuccess">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4" id="contactError">
<strong>Error!</strong> There was an error sending your message.
<span class="mail-error-message text-1 d-block" id="mailErrorMessage"></span>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<label for="name" class="required font-weight-bold text-dark">Full Name</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
</div>
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Email Address</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<label class="font-weight-bold text-dark">Phone</label>
<input type="text" value="" data-msg-required="Please enter the phone number." maxlength="100" class="form-control" name="phone" id="phone" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<label class="required font-weight-bold text-dark">Message</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="5" class="form-control" name="message" id="message" required></textarea>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<div class="g-recaptcha" data-sitekey="Your_Public_Key"></div>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<input type="submit" value="Send Message" class="btn btn-primary btn-modern" data-loading-text="Loading...">
</div>
</div>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/view.contact.js"></script>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
else {
$("#submit-btn .text").text("Enviado");
$("#submit-btn").addClass("active");
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<script>
$("#contactForm").validate();
</script>
</body>
</html>
The issue
I have the issue that when the user hits submits, everything goes as planned, and the form refreshes, and the success message appears, but the form refreshes with validation showing red boxes, which is the problem I want to solve. This is how a successful form submission currently looks like and this is incorrect:
<img src="https://i.stack.imgur.com/eV7A6.png" width="50%" height="50%" />
When the user hits submit, I want the user to see the success message; I want the form to refresh without green or red boxes to the input fields. To better understand this, please have a look at the below behavior I want to achieve:
<img src="https://i.stack.imgur.com/0Yf01.png" width="50%" height="50%" />
I know that the issue is in the JavaScript for disabling form submissions (above) or in the view.contact.js:
I appreciate any insights or guidance about how I can fix this.
One more question I have is this: Will I need the below code?
<script>
$("#contactForm").validate();
</script>
Any comment on how to make this code better is highly appreciated.
From the official documentacion:
To reset the appearance of the form (for instance, in the case of
dynamic form submissions using AJAX), remove the .was-validated class
from the again after submission.
Bootstrap > Form > Validation > How it Works
In your case, you need to add the following line:
$form.removeClass('was-validated');
Inside:
$.ajax({...})
.done(function() {
//HERE
),
.always({...});

Click a element On Enter

there I am working on a project for the login form.
I need to write a code that when the user pressed Enter on the Keyboard in input X code Call the function Y.
I saw Many Pages on Stackoverflow but theirs not working for me. I use Jquery In my project.
<div class="main">
<h2 class="title"><br> Wikipedia Image Finder!</h2>
<div class="form">
<label class="S_label" for="input_data"> <span class="Label_text">Image Title:</span> </label>
<div class="ll">
<input name="input" type="text" maxlength="999" id="input_data" minlength="1" placeholder="Query to Search" required>
<div class="img_btn" id="submit_div""></div>
</div>
</div>
</div>
Please try below code.
$("input").keyup(function(event){
// checking the pressed key is Enter
if(event.which == 13) {
search(event.target.value);
}
});
function search(text){
alert('called search with '+ text)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main"> <h2 class="title"><br> Wikipedia Image Finder!</h2> <div class="form"> <label class="S_label" for="input_data"> <span class="Label_text">Image Title:</span> </label> <div class="ll"> <input name="input" type="text" maxlength="999" id="input_data" minlength="1" placeholder="Query to Search" required> <div class="img_btn" id="submit_div""></div> </div></div> </div>

Submit button is not working with HTML and JavaScript

Whenever I attempt to click the submit button, nothing happens.
I have attempted to change the button, however I doubt this is the issue.
JavaScript Code:
$('#contactForm').submit(function () {
$.ajax({
type: "POST",
url: "php/contact.php",
data: $('#contactForm').serialize(),
success: function (msg) {
if (msg == 'SEND') {
$('.success').fadeIn();
$('.error').fadeOut();
$('#contactForm')[0].reset();
} else {
$('.success').fadeOut();
$('.error').fadeIn().find('h3').text(msg);
}
}
});
return false;
});
HTML Code:
<div>
<h2 class="small-heading">CONTACT US</h2>
<div class="contact-form col-sm-11 clearfix">
<form action="contact-complete.php" id="contactForm" method="post" name="contactForm">
<fieldset>
<div class="col-sm-12">
<input id="name" name="name" placeholder="Your Name*" type="text" value="">
</div>
<div class="col-sm-12">
<input id="email" name="email" placeholder="Your Email*" type="text" value="">
</div>
<div class="col-xs-12">
<textarea cols="5" id="message" name="message" placeholder="Your Message....*"></textarea>
</div>
<div class="col-xs-12">
<button type="submit" form="contactForm" class="submit active">SEND</button>
</div>
<div class="error col-xs-12">
<h3></h3>
</div>
<!-- Error Message [ END ] -->
<div class="success col-xs-12" id="update">
<h3>Success! Your message was sent.</h3>
</div>
<!-- Submit Button [ END ] -->
</fieldset>
</form>
<!-- Contact Form [ END ] -->
</div>
</div>
If you could please help me out this would be much appreciated.
Thank you for all of your help.
This seems to be an issue within the AJAX call. I removed "return false;" from the code and it seemed to work. However, it was sending the information twice. So I just removed the AJAX code all together and it worked just fine redirecting to the PHP mail() script.
Thanks for all of your help.
Your button doesnt have an action and you don´t listen for it either
<button type="submit" form="contactForm" class="submit active" OnClick="submit()">SEND</button>
Or add an ID and listen for that in the JS

How to perform client-side form-validation on password

I am doing a simple sign-up page. For the password stuff, I need to check the new password and confirmed password are the same but no idea how
<div class="row">
<!--New Username-->
<div class="large-4 columns form-text">New Username</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="text" class="form-input" name="username" required>
</div>
</div>
<br/>
<div class="row">
<!--New email-->
<div class="large-4 columns form-text">Email</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="email" class="form-input" name="email" pattern="[a-zA-Z]*#[a-zA-Z]*" required>
</div>
</div>
<br/>
<div class="row">
<!--New Passwrord-->
<div class="large-4 columns form-text">New Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password" required>
</div>
</div>
<br/>
<div class="row">
<!--Reconfirm new password-->
<div class="large-4 columns form-text">Re-enter Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password-confirm" required>
</div>
</div>
That's quite a bit of code, but I broke out an example on a fiddle.
Simplified HTML:
<form id="passwordForm" action="#" method="POST">
Password:<br>
<input type="password" id="password"><br>
Confirm Password:<br>
<input type="password" id="confirmPassword"><br>
<input type="submit" id="submitButton" value="Check 'Em">
</form>
<div id="responseDiv"></div>
I used jQuery:
$(document).ready(function () {
$("#submitButton").click(function (e) {
e.preventDefault();
var matched,
password = $("#password").val(),
confirm = $("#confirmPassword").val();
matched = (password == confirm) ? true : false;
if(matched) {
//Submit line commented out for example. In production, remove the //
//$("#passwordForm").submit();
//Shows success message and prevents submission. In production, comment out the next 2 lines.
$("#responseDiv").html("Passwords Match");
return false;
}
else {
$("#responseDiv").html("Passwords don't match...");
return false;
}
});
});
Many times new learners will forget the e.preventDefault(); Without it, the form will submit regardless of any validation. Return false if there is something wrong, and the form will not submit.
There is an event listener on the submit button. If it is clicked, or the enter key is pressed will focused in the form, it will run the validation. If everything is fine, it will post the information to the URL in the action attribute of the form tag.
Another important point is to always re-validate on the server side. If a user has their Javascript turned off the form will post the information regardless of what is in your validation script.
with normal javascript, just adapt to your source code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function pass() {
var pass_1 = document.forms["myForm"].pass_1.value.length;
var pass_2 = document.forms["myForm"].pass_2.value.length;
if (pass_1 != pass_2) {
alert("the pass and repeat pass must be equal");
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="" name="myForm" onSubmit="pass(); return false;">
<input type="password" placeholder="type your pass" name="pass_1">
<input type="password" placeholder="confirm your pass" name="pass_2">
<input type="submit" value="validate">
</form>
</body>
</html>
the same code above but with the redirect: http://jsfiddle.net/m7BrM/
option 2 use a plugin:
http://www.technicalkeeda.com/jquery/password-and-confirm-password-validation-in-jquery

User Registration - Validation & Storing

I have started to write the validation for user registration. This form is so users can register on the site, however I'm having issues with how to properly write validation for each field.
so far:
<div id="content">
<div class="ic"></div>
<div class="inner">
<div class="container_12">
<div class="wrapper">
<div class="grid_12">
</div>
</div>
<div class="wrapper">
<div class="grid_12">
<h2 class="h-pad1">Open an Account with Us</h2>
<form action="" id="validate" class="form" method="POST">
<fieldset>
<div class="formRow">
<label for="login">Username:</label>
<div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Password:</label>
<div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Repeat Password:</label>
<div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Email:</label>
<div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div>
<div class="clear"></div>
</div>
What would be the proper code to add? Thank you.
Your most important task is to learn how to use document.getElementById() if your going to be using regular javascript. With that function you can grab the value in the different fields and check what is stored in them.
I would have a highlevel function validateRegistrationForm() that calls functions for validating each field. For example
function validateRegistrationForm(){
if(!validateEmailField()) // Invalid email format
return;
if(!validatePasswordField()) // Invalid password length
return;
if(validateUserNameField()) // invalide characters in email
return;
.
.
etc.
}
function validateEmailField(){
var x=document.getElementById("email").value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
errorPopup("Not a valid e-mail address");
return false;
}
if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored.
return true;
return isEmailUnique(); // return true if the email is unique
}
You can have something like:
function validate()
{
var uName = document.getElementById('username');
if(uName == '' or uName=' ')
{
// do something
}
repeat for other elements.
.
.
.
.
// in the end, you can return true; if all validation condition meet or else return false;
}

Categories