javascript validateform() function not validating form - javascript

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();

Related

jQuery .on('submit', function(e) how to add extra input value + checkbox validation

I'm building a simple form but I'm stuck:
if I send only the email field, the form validates the email and sends it
if I add two fields I can't get it to work:
name
checkbox (GDPR)
I need to add the validation that the name field is not empty, and that the checkbox field is checked
$(document).ready(function($) {
var jsForm = $('.js-form-download');
jsForm.on('submit', function(e) {
var email = $(this).find('input[type=text]').val();
if (!validateEmail(email)) {
e.preventDefault();
jsForm.addClass('form-error');
}
});
// VALIDATION BEGIN
function validateEmail(email) {
var re = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
return re.test(email);
}
//VALIDATION END
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form accept-charset="UTF-8" action="/form.php" method="POST" class="main-download-form text-center js-form-download">
<input class="infusion-field-input-container" id="CustomFields_2_1" name="CustomFields[2]" type="text" placeholder="Enter Your Name" autocomplete="off" required="">
<input class="infusion-field-input-container" id="inf_field_Email" name="email" type="text" placeholder="Enter Your Email Address" autocomplete="off" required="">
<!-- field GDPR 1 REQUIRED -->
<div class="form-single--checkbox" style="max-width:400px; margin: 0 auto 20px;">
<label style="font-weight:normal;"><input type="checkbox" id="pcheck" style="width:18px; height: 18px; margin-left:0%; margin-bottom:0px;"/>Accetto il Regolamento della <strong>Privacy</strong>
</label>
</div>
<input class="btn-full" type="submit" value="Continue...">
</form>
Your issue is here var email = $(this).find('input[type=text]').val();
this will give you the first INPUT element's .val(), and if you take a closer look, the first INPUT in your form is actually the name
<input class="infusion-field-input-container" id="CustomFields_2_1" name="CustomFields[2]" type="text" placeholder="Enter Your Name" autocomplete="off" required="">
So, not the email one.
Instead, use:
var email = $(this).find('[name=email]').val();
Or, since you already use ID selectors in your HTML
var email = $("#inf_field_Email").val();

Signup page button isn't redirecting me to another page

<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>

Password verification for webpage in html and javascript

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;

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

form validation using java script

Following form validates using JavaScript,but its not working. It still takes action,instead of showing error.I cant figure out what is wrong with code. It seems fine. Can anyone show me my mistakes?
<script type='text/javascript'>
function formValidator(){
var name = document.getElementById('name');
var alpha = /^[a-zA-Z]+$/;
if(!alpha.test.(name.value)){
alert('Please provide a valid name');
name.focus;
return false;
}
var email = document.getElementById('email');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
<div id="contact_form">
<p>Stay Connected.</p>
</div>
<form name="contact" method="post" action="sendmail.php" onsubmit='return formValidator();'>
<fieldset>
<label for="name" id="name_label">Your name *</label>
<input type="text" name="name" id="name" size="50" value="" class="text-input" required />
<label for="email" id="email_label">Your email address *</label>
<input type="text" name="email" id="email" />
<br />
<input type="submit" name="submit" class="button btn btn-primary btn-info" id="submit_btn" value="Send" onclick='Javascript:formValidator();'/>
</fieldset>
</form>
I dont want to use only html5 validation.
This is the error in console
SyntaxError: missing name after . operator
[Break On This Error]
if(!alpha.test.(name.value)){
so use
if (!filter.test(name.value)) instead of if(!alpha.test.(name.value)){
remove .
I guess the if statements are never true, so false is never returned.
replace if (!filter.test.(name.value)) {
to
if (!filter.test(name.value)) {

Categories