I have a registration webpage where a user inputs information like name and password. There are two inputs for password to verify they are the same password but when I submit the form, it says the passwords don't match, even when they do.
<form id="registration-info" method="POST" action="/registration" >
...
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
<script>
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
repeat_password.setCustomValidity('');
}
}
</script>
</div>
There are two problems with your code.
You've put your validation code in an onclick handler on the <form> element. This means the script will never run at all, because the user doesn't click on the <form>, they click on the submit <button>. Instead use an onsubmit handler on the form.
You aren't doing anything to prevent the form from submitting if the password values don't match. One way to do this is to return false from the onsubmit handler.
Here is a corrrected version:
form = document.getElementById("registration-info");
form.onsubmit = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if (password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
console.log("Passwords don't match");
return false; // prevent the form from submitting
} else {
repeat_password.setCustomValidity('');
}
}
// reset the customValidity when the field is modified, so corrected
// values won't trip up on past errors:
document.getElementById("repeat_password").onchange = function(e) {
e.target.setCustomValidity('')
}
.invalid-feedback {display:none}
<form id="registration-info" method="POST" action="/registration">
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
</div>
<input type="submit" value="Submit" id="registration-info-submit">
</form>
Another way to do this -- and to be honest if I'd been familiar with setCustomValidity before this question, this probably would have been my answer in the first place -- might be to set the customValidity message values when the field values change, instead of on form submit. (If a customValidity value is set, it will prevent the form submit from running at all.)
document.getElementById("registration-info").onchange = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if (password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
repeat_password.setCustomValidity('');
}
}
<form id="registration-info" method="POST" action="/registration">
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
</div>
<input type="submit" value="Submit" id="registration-info-submit">
</form>
(But note that this will leave your forms unvalidated in IE9 and below, which do not support setCustomValidity; the first snippet will validate the form in all browsers.)
You did not take the values of the selected ids here. Inatead of taking values after in IF case try the following code. I hope that is the only reason.
var password = document.getElementById("password").value;
var repeat_password = document.getElementById("repeat_password").value;
Related
<body>
<h1 style="color:red;">SIGN UP</h1>
<p style="color:blue;">Please fill in this form to create an account.</p>
<label for="Email">Email:</label>
<input type="text" id="Email" name="Email"><br><br>
<label for="password">password:</label>
<input type="text" id="password" name="password"><br><br>
<label for="repeatpassword">repeatpassword:</label>
<input type="text" id="repeatpassword" name="repeatpassword"><br><br>
<button onclick="email" >SIGNUP!</button>
<script>
var email = document.getElementById("Email").value;
function email(){
if(document.getElementById("password").value===document.getElementById("repeatpassword").value && email.include("#")== true){
location.href = "question2.html";
}
}
</script>
</body>
</html>
I want to redirect to another html page when clicking on signup button and email input field contains "#" and password input field value is same as repeatpassword but I don't know what is wrong with my code
Check out with window.location.href in the script function to redirect.
for more reference look out https://www.w3schools.com/js/js_window_location.asp
Button onclick="email()" parenthesis is required because you are calling a function on a button click.
Function can't access a variable declared outside the function. So declare that email var inside the function scope.
It's not email.include() function it's includes(). "s" was missing. Ref -
https://www.w3schools.com/jsref/jsref_includes.asp
function email(){
var email = document.getElementById("Email").value;
if(document.getElementById("password").value===document.getElementById("repeatpassword").value && email.includes("#")== true){
console.log("Working");
}
else{
console.log("Not working");
}
}
<h1 style="color:red;">SIGN UP</h1>
<p style="color:blue;">Please fill in this form to create an account.</p>
<label for="Email">Email:</label>
<input type="text" id="Email" name="Email"><br><br>
<label for="password">password:</label>
<input type="text" id="password" name="password"><br><br>
<label for="repeatpassword">repeatpassword:</label>
<input type="text" id="repeatpassword" name="repeatpassword"><br><br>
<button onclick="email()" >SIGNUP!</button>
When I enter invalid details the website doesn't show up with any errors and it sumbits the form
I've tried putting onsubmit on the form tag and onclick on the button tag but nothing works
it should come up with an error when I type in an invalid email or postcode or the passwords dont match
also I would like it so that when the user inputs numbers for the first name or last name it comes up with an error
<form class="modal-content" action="register.php" method="post" name="myform">
<div class="signup-container">()
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<div class="fbox">
<label for="fn"><b style="font-size:14px;">First Name</b></label>
<input type="text" id= "First_Name" placeholder="Enter First Name" name="fname" required>
</div>
<div class="sbox">
<label for="ln"><b style="font-size:14px;">Last Name</b></label>
<input type="text" id= "Last_Name" placeholder="Enter Last Name" name="lname" required>
</div>
<div class="tbox">
<label for="email"><b style="font-size:14px;">Email</b></label>
<input type="text" id="Email" placeholder="Enter Email" name="email" required>
</div>
<div class="fobox">
<label for="pc"><b style="font-size:14px;">Post Code</b></label>
<input type="text" id="pcode" placeholder="Postcode" name="pcode" required>
</div>
<div class="fibox">
<label for="psw"><b style="font-size:14px;">Password</b></label>
<input type="password" id="pass" placeholder="Enter Password" name="pass" required>
</div>
<div class="sixbox">
<label for="psw"><b style="font-size:14px;">Confirm Password</b></label>
<input type="password" id="UserPassword" placeholder="Confirm Password" name="UserPassword" required>
</div>
<label class="remember">
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button onclick="validateform()"type="submit" name="Submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
<script>
function validateform(){
var Firstname = document.querySelector( "#First_name"); //sets the variable name as the value entered by the user
var Lastname = document.querySelector( "#Last_Name"); //sets the variable name as the value entered by the user
var password = document.querySelector( "#pass");//sets the variable password as the value entered by the user
var confirmpassword = document.querySelector( "#UserPassword");//sets the variable confirmpassword as the value entered by the user
var email = document.querySelector( "#Email");//sets the variable email as the value entered by the user
var atposition = email.indexOf("#");
var dotposition = email.lastIndexOf(".");
var postcode = document.querySelector("pcode");//sets the variable postcode as the value entered by the user
function alertMessage(messageObject) {
alert(messageObject);
return true;
}
if (Firstname==null){
alertMessage("Firstname can't be blank"); //makes sure that the name is not empty
return false;
}else if (Lastname==null){
alertMessage("Lastname can't be blank"); //makes sure that the name is not empty
return false}
else if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email.length){
alertMessage("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition); //makes sure email is in the right format
return false;
}
function valid_postcode(postcode){
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
}
valid_postcode(postcode)
if(password.length<8){
alertMessage("Password must be at least 8 characters long."); //makes sure password is above 8 characters
return false;
}
else if(password!==confirmpassword){
alertMessage("password must be same!"); //makes sure that the passwords match
return false;
}
}
You should change your html type code from "submit" to "button", for the page not submit by it self. And put a id="myform" in your form.
<form class="modal-content" action="register.php" method="post" name="myform" id="myform">
<button onclick="validateform()" type="button" name="Submit" class="signupbtn">Sign Up</button>
And put this code on your javascript, you could do a verification to check if everything is ok, then you call this function to submit your form.
javacript
document.getElementById('myForm').submit();
I have a form to submit several fields. Two of them are for changing a password.
These password fields aren't required to be filled out before submitting. However, if one of them isn't blank I add the required attribute to both fields when it's changed through jQuery. I remove the attributes when I empty one and the other is already empty too.
The thing it seems to work the most of the times with an exception:
I fill out password
password2 is blank
I submit the form
In this case the validation for password2 shows up, but if I want to remove everything and submit, I can't:
I remove password
I submit the form again
The validation for password2 shows up again. Even if the 'required' attributed is removed in the HTML source
This is the HTML code:
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
And the jQuery code:
$('#password').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$( '#password2' ).attr('required', true);
}else{
if($('#password2').val() == ''){
$(this).removeAttr('required');
$( '#password2' ).removeAttr('required');
}
}
});
$('#password2').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$('#password').attr('required', true);
}else{
if($('#password').val() == ''){
$(this).removeAttr('required');
$('#password').removeAttr('required');
}
}
});
And it's an example in JSFiddle:
https://jsfiddle.net/jke3pgh0/
I will suggest you a different approach here...
First, you only need one handler for this, since the logic is the same for both inputs. You can use more than one selector... Ex: $('#password, #password2'). But I would use a class instead... Like $(".password"). It's up to you.
Second, I said the «logic is the same»... That is:
If one of the two inputs is not empty, both are required.
So having the same change event handler on both inputs mean you don't really know which one triggered the event. So I suggest to use an .each() loop here (to make sure you check all values)... and a boolean "flag" (true/false).
After that loop, use that "flag" to set the required attribute.
I used a CSS rule to make the result obvious in the snippet below.
$('#password, #password2').change(function(){
// Look up for the password inputs in that "row".
var pass_inputs = $(this).closest(".row").find("[type='password']");
// Flag to determine if at least one is not empty.
var not_empty = false;
// Loop throug the password inputs and change the flag.
pass_inputs.each(function(){
if($(this).val() != ''){
not_empty = true
}
});
// Use the flag as the boolean argument for the required attribute.
pass_inputs.attr('required', not_empty);
});
[required]{
border: 3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
i'm working with the forms and i want when i hit the submit buttom only that field gets red which are empty . don't knw how to fix it . if anyone can help me i'm new javascript and jquery thanks
My HTML
<form id="form">
<div class="form-group">
<label>Username</label>
<p><span id="usernameError"></span></p>
<input type="text" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label>Email</label>
<p><span id="emailError"></span></p>
<input type="email" class="form-control" id="email" placeholder="email">
</div>
<div class="form-group">
<label>Password</label>
<p><span id="passwordError"></span></p>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<p><span id="confPasswordError"></span></p>
<input type="password" class="form-control" id="confPassword" placeholder="Confirm Password">
</div>
<p><span id="warning"></span></p>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
MY JAVASRIPT
now here is the situation . i put all the variables in one if statement and that's why they all are turning into red
$("#form").submit(function(){
if(password.val() != confPassword.val() )
{
alert("password dont match");
}
if($(this).val() == ""){
username.addClass("border");
email.addClass("border");
password.addClass("border");
confPassword.addClass("border");
// warning message
message.text("PLEASE FILL OUT ALL THE FIELDS").addClass("boldred");
// errors rendering
usernameError.text("username must be defined").addClass("red");
emailError.text("email must be valid and defined").addClass("red");
passwordError.text("password must be defined").addClass("red");
confPasswordError.text("confirm password must be matched and defined").addClass("red");
// disabling submit button
submit.attr("disabled" , "disabled");
return false;
}
else{
return true;
}
});
Try JQuery Validation Engine. Its very easy to implement your form.
Validation Engine
Supported for all browsers
First try adding required to all the necessary fields, like:
<input type="text" class="form-control" id="username" placeholder="Username" required>
Then disable (or delete) the if clause.
If that doesn't work, just let me know in the comments and I'll update the answer.
You are approaching the problem in incorrect way.
On Form submit you need to check each field you want separately.
For example:
$("#form").on('submit', function() {
var submit = true;
$(this).find('span').removeClass('red');
$(this).find('input').each(function() {
if ($.trim($(this).val()) === '') {
submit = false;
$(this).parents('.form-group').find('span').addClass('red');
}
});
return submit;
});