Onsubmit not working - javascript

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?

First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>

For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.

First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

Related

Why is my form not returning an alert when password does not match the confirm password field Javascript?

So I'm new to JS, and I'm trying to make this form prevent submission if password does not match the confirm password field. However, when I enter in 2 different passwords, I don't get an alert like I've coded in the script below. Any thoughts? For reference, the form was built w/ bootstrap.
<form class="form-signin">
<div class="form-label-group">
<input type="text" id="fullName" class="form-control" placeholder="Username" required autofocus>
<label for="fullName">Full name</label>
</div>
<div class="form-label-group">
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required>
<label for="inputEmail">Work email</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputConfirmPassword" class="form-control" placeholder="Password" required>
<label for="inputConfirmPassword">Confirm password</label>
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase" id ="register-btn" type="submit">Register</button>
<hr class="my-4">
<div class="registration-login">
<p class="already-have__account">Already have an account?</p> Login
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="registration__section">
<h2>Innovative supply chain teams use Rumi to manage scalable and sustainable packaging.
</h2>
</div>
<script>
var form = document.getElementById('form-signin');
form.onsubmit = function() {
if (inputPassword.value !== inputConfirmPassword.value) {
alert("Your passwords don't match");
return false;
}
else {
return true;
}
}
Just a minor mistake.
You are using get getElementById.
var form = document.getElementById('form-signin');
There is no id with 'form-signin',
<form class="form-signin">
Rename the class to id.
<form id="form-signin">
Check out this (JSFiddle). It's working here.

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

How to trigger default Bootstrap 4 form validation error message from custom external script

In our contact form, I'm trying to only allow submissions from email addresses from the United States, since we can only do business in that one country. How can I trigger the default error message when a form submit attempt is made, so that "invalid" message appears the same way it appears for the first name and last name fields?
In the code below, for the sake of example, I'm allowing only 'com', 'edu', 'gov', 'net', 'org'. The goal is to trigger a message whenever an email address other than those above is entered into the email field.
$(document).ready(function() {
$(function() {
$("#testform").submit(function() {
str = $('input[name=emailAddress]').val();
str = str.split('#').slice(0);
str = str[1].split('.').slice(0);
var allowedDomains = ['com', 'edu', 'gov', 'net', 'org'];
alert("str = " + str[1]);
if ($.inArray(str[1], allowedDomains) !== -1) {
alert(str + ' is allowed');
} else {
alert('not allowed');
event.preventDefault();
event.stopPropagation();
$('#emailAddress').addClass('invalid');
}
});
});
});
<link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/holder.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/dist/js/bootstrap.min.js"></script>
<script src="https://getbootstrap.com/docs/4.0/assets/js/vendor/popper.min.js"></script>
<div class="container">
<form action="" method="post" target="" class="needs-validation" role="form" id="testform">
<fieldset>
<div class="form-group">
<label for="firstName" class="col-form-label">Customer first name:
<input type="text" class="form-control" name="firstName" id="firstName" required aria-required="true">
</label>
</div>
<div class="form-group">
<label for="lastName" class="col-form-label">Customer last name:
<input type="text" class="form-control" name="lastName" id="lastName" required aria-required="true">
</label>
</div>
<div class="form-group">
<label for="emailAddress" class="col-form-label">Customer email address:
<input type="email" class="form-control" name="emailAddress" id="emailAddress" required placeholder="Enter valid email" aria-required="true">
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
</div>

Javascript not running on php page

So I am making a web based application that needs to have the ability for an admin user to create sub users. I have the sql database working correctly when I create a user but the issue is that when I go ahead and add a user, it redirects me to a different php page. With the javascript running, it normally just says successful when I change password or change username. Here's the code.
<!-- create username -->
<form action="php_action/createUsername.php" method="post" class="form-horizontal" id="createUsernameForm">
<fieldset>
<legend>Create Username</legend>
<div class="createUsenrameMessages"></div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label">New User</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="usernameC" name="usernameC" placeholder="username" value="<?php echo $result['username']; ?>"/>
</div>
</div>
<div class="changePasswordMessages"></div>
<div class="form-group">
<label for="npassword" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="npasswordC" name="npasswordC" placeholder="New Password">
</div>
</div>
<div class="form-group">
<label for="cpassword" class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="cpasswordC" name="cpasswordC" placeholder="Confirm Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" name="user_id" id="user_id" value="<?php echo $result['user_id'] ?>" />
<button type="submit" class="btn btn-success" data-loading-text="Loading..." id="createUsernameBtn"> <i class="glyphicon glyphicon-ok-sign"></i> Add User </button>
</div>
</div>
</fieldset>
</form>
here is the script
// create username
$("#createUsernameForm").unbind('submit').bind('submit', function() {
var form = $(this);
var username = $("#usernameC").val();
var newPassword = $("#npasswordC").val();
var conformPasswordPassword = $("#cpasswordC").val();
if(newPassword == "" || conformPassword == "") {
if(newPassword == "") {
$("#npasswordC").after('<p class="text-danger">The Current Password field is required</p>');
$("#npasswordC").closest('.form-group').addClass('has-error');
} else {
$("#npasswordC").closest('.form-group').removeClass('has-error');
$(".text-danger").remove();
}
if(conformPassword == "") {
$("#cpassword").after('<p class="text-danger">The Conform Password field is required</p>');
$("#cpassword").closest('.form-group').addClass('has-error');
} else {
$("#cpassword").closest('.form-group').removeClass('has-error');
$(".text-danger").remove();
}
return false;
});

javascript validation for register page not working

I don't know what's wrong in this. Validation not working here.
Form submitted without validation.
function validate()
{
if( document.myForm.username.value == "" )
{
alert( "Please provide your user name!" );
document.myForm.fname.focus() ;
return false;
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.myform.email.value))
{
alert("You have entered an invalid email address!")
return false;
}
}
return false;
}
<form class="form-horizontal" method="post" id="myForm" action=" " name="myForm" onsubmit="return validate()">
<div class="form-group">
<p class="text-center">Register Information</p>
<br>
</div>
<div class="form-group">
<label for="username" class="control-label col-xs-2">UserName</label>
<div class="col-xs-2">
<input type="text" class="form-control" id="name" name="username"
placeholder="UserName">
</div>
</div>
<div class="form-group">
<label for="email" class="control-label col-xs-2">Email Address</label>
<div class="col-xs-2">
<input type="text" class="form-control" name="email" id="email"
placeholder="abc#domain.com" />
</div>
</div>
<div class="form-group">
<label for="password" class="control-label col-xs-2">Password</label>
<div class="col-xs-2">
<input type="password" class="form-control" name="password" id="password"
placeholder="##########" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button type="submit" name="submit" class="btn btn-primary">submit</button>
</div>
</div>
</form>
I don't know whats wrong in this.Please help me to fix it.
Try using type="email" form email id field validation and 'required' directive for required fields.
<input type="email" class="form-control" name="email" id="email" placeholder="abc#domain.com" required/>
If you tried to do validation using HTML5 features you have to add attrributes like required or pattern to your inputs.
You trigger validate() on submit bu there is no javascript code in the markup you pasted.
Start with this article.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation
It describes native browser support for valdiation and later suggests some libraries and examples of custom code.
In validate function the closing bracket just before the last "return false" statement is unnecessary.

Categories

Resources