I have a PHP file containing a HTML registration form. The form consists of a few fields including a phone number, password and repeat password field.
I would like these fields to be validated and require some guidance on how to validate the users input. These fields should be required and the two password fields should match.
If it fails validation I would like the user to have feedback and the form to be prevented from being submitted.
If it passes then the form should be submitted.
<div id="id02" class="modal">
<form class="modal-content animate" action="register.php" method="post">
<div class="imgcontainer">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">×</span>
</div>
<div class="container">
<label><b>Name:</b></label>
<input type="text" placeholder="Enter Name" name="name" required>
<label><b>Phone No.:</b></label>
<input type="text" placeholder="Enter Phone number" name="phone" required>
<label><b>Date of Birth:</b></label>
<input type="date" placeholder="Enter Date of Birth" name="dob" required>
<label><b>E-mail:</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Password:</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label><b>Repeat Password:</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="register">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</div>
</form>
<script>
// Get the modal
var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event)
{
if (event.target == modal)
{
modal.style.display = "none";
}
}
</script>
Taken from https://www.w3schools.com/js/js_validation.asp (one of the first google results when googling for your question. You might want to do so yourself the next time).
You might want to adapt your code like this:
<form class="modal-content animate" action="register.php" onsubmit="return validateForm()" name="formToValidate" method="post">
[...] your other code [...]
function validateForm() {
// get value of phone number field
var x = document.forms["formToValidate"]["phone"].value;
// check phone number for being empty
if (x == "") {
alert("Phone number must be filled in");
// return false to interupt the POST request.
return false;
}
// copy, paste and adapt for the other form elements
}
Related
How do I write a function that overrides form validation when a user clicks the back button?
If the user doesn't fill the form and clicks submit, it tells shows " please fill in this field"
then I added a back button in case the user doesn't wanna fill the form and wants to go back
but onClick it shows "please fill in this field"
how do I override this when the user clicks back?
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
function goBack() {
window.history.back()
}
<div class="form-div">
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post" required>
<button onclick="goBack()">Go Back</button>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="name"><b>FullName</b></label>
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" name="fullName" id="name" required>
<label for="email"><b>Email</b></label>
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email" name="email" id="email" required>
<label for="psw"><b>Password</b></label>
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
<p>By creating an account you agree to our Terms & Privacy.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? Sign in.</p>
</div>
</form>
</div>
I think removing the "required" attribute from your form tag should be good even if you keep this "required" attribute on your inputs.
This thing happen because you added button inside <form> that causing it to act as a submit button
see this: How to prevent buttons from submitting forms
so basically you can return false, but its much easer to just remove the button outside the <form>
FYI
You should ALWAYS check the values of the inputs buy yourself because everyone who is familiar with the devTools can delete the required attribute and then send empty values to your server
Another FYI
You must check the values also in the server because there are many ways you can override the client checks (you do the client side check just for UX)
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.
Here, I am trying to use the signUp() function to get the users details and store them into the database. I already tested the backend Javascript file (signUp function) using postman and it works perfectly fine.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link href="css\signup.css" rel="stylesheet" type="text/css">
<script>
function signUp() {
if (document.getElementById("password2").value == document.getElementById("cfmpassword2").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username2 = document.getElementById("username2").value;
users.email = document.getElementById("email").value;
users.password2 = document.getElementById("password2").value;
var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details
postUser.open("POST", "/users", true); //Use the HTTP POST method to send data to server
postUser.setRequestHeader("Content-Type", "application/json");
// Convert the data in "users" object to JSON format before sending to the server.
postUser.send(JSON.stringify(users));
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
</script>
</head>
<body>
<div style="margin-top: -703px; margin-left: 1250px; position: absolute;">
<!-- Sign up button -->
<p>Need an account?
<button class="signup" id='signup' onclick="document.getElementById('id02').style.display='block'" style="width:auto; height: 6.1vh;">
Sign Up
</button>
</p>
</div>
<!-- The Sign Up Modal-->
<div id="id02" class="modal2">
<span onclick="document.getElementById('id02').style.display='none'" class="close2" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username2" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password2" placeholder="Enter Password" name="psw" required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword2" placeholder="Confirm Password" name="psw-confirm" required>
<br>
<br>
<p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<button type="submit" class="signupbtn" onclick="signUp()">Sign Up</button>
</div>
</div>
</form>
</div>
</body>
</html>
If Confirm Password matches Password, I will get the user details and send the data to my database server. Else, an alert msg is supposed to pop up.
However, I after trying it out, I see nothing being added into my database. My else part works though, an alert message does pop up on my browser.
Is this due to an error about the Confirm Password? Because I have a very similar set of working codes except that it doesn't contain the Confirm Password column. I got the confirm password from here how to check confirm password field in form without reloading page
Could someone please help identify the problem? Thanks a lot!
You are calling signUp() when a submit button is clicked.
The JavaScript runs, but as the XHR request is being prepared, the form is submitted, the browser navigates, and the XHR request is canceled.
Don't use a submit button if you aren't submitting the form.
Your comment that changing the submit to a regular button prevents you from actually being able to click it seems a little odd. The below code has a standard button and seems OK which suggests a css issue perhaps. I tested this with a php endpoint and the request was sent OK so it ought to be find hitting your javascript endpoint - unless there is another factor (css most likely ) interfering with the button
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link href="css/signup.css" rel="stylesheet" type="text/css">
<script>
function signUp(event) {
event.preventDefault();
if (document.getElementById("password2").value == document.getElementById("cfmpassword2").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username2 = document.getElementById("username2").value;
users.email = document.getElementById("email").value;
users.password2 = document.getElementById("password2").value;
var postUser = new XMLHttpRequest();
/*
Optional:
A callback to process response from the server and possibly manipulate the DOM
or let the user know if things went OK.
*/
postUser.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 ){
alert( this.response )
}
}
postUser.open( "POST", "/users", true );
postUser.setRequestHeader( "Content-Type", "application/json" );
postUser.send( JSON.stringify( users ) );
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
</script>
</head>
<body>
<div style="margin-top: -703px; margin-left: 1250px; position: absolute;">
<!-- Sign up button -->
<p>Need an account?
<button class="signup" id='signup' onclick="document.getElementById('id02').style.display='block'" style="width:auto; height: 6.1vh;">
Sign Up
</button>
</p>
</div>
<!-- The Sign Up Modal-->
<div id="id02" class="modal2">
<span onclick="document.getElementById('id02').style.display='none'" class="close2" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username2" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password2" placeholder="Enter Password" name="psw" required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword2" placeholder="Confirm Password" name="psw-confirm" required>
<br>
<br>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<!--
modify the button to a standard button rather than a submit
- this enables the ajax function to do what is intended.
An alternative would be to invoke `event.preventDefault()` within
the signUp(event) function to stop the submit button from actually
submitting the form
-->
<button type="button" class="signupbtn" onclick="signUp(event)">Sign Up</button>
</div>
</div>
</form>
</div>
</body>
</html>
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";
}
?>
How go get an input text value in JavaScript?
I want to get input text value in jquery script but it prompted empty.
my script code:
<script type="text/javascript">
var emails;
function checkRegistration() {
emails = document.getElementById('my_email').value;
alert(emails);
}
</script>
my form code :
<form method="post" role="form" onSubmit="return checkRegistration()" action="#">
<div class="form-group">
<input type="email" class="form-control" id="my_email" name="email" placeholder="Enter a valid email address">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary btn-block" value="Forgot Password" />
</div>
</form>
First check are you using jquery.min.js file or not.
Second if you want to get value using id. id should be unique on that page.
Try below
var my_email= $('#my_email').val();
Edit, Updated
Add required attribute to input type="email" element, to prevent form submission if value not entered by user
Use .onchange event
var emails = document.getElementById("my_email");
function checkRegistration() {
alert(this.value);
}
emails.onchange = checkRegistration;
<form method="post" role="form" action="#">
<div class="form-group">
<input type="email" class="form-control" id="my_email" name="email" placeholder="Enter a valid email address" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary btn-block" value="Forgot Password" />
</div>
</form>