I have a problem with validation.
I wanted show text'fill the field' after every wrong fill input on submit. And I have a problem with validation email I dont have any idea how I should do this.
JS
function onclickHandler() {
var form = document.querySelector("#myForm"),
fields = form.querySelectorAll(".requiredField"),
error = form.querySelector(".error");
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (field.value == "") {
error.innerHTML = '<p>Fill this field</p>';
} else {
console.log('ok');
error.remove();
}
}
}
HTML:
<div class="form-contact">
<div class="item">
<input type="text" placeholder="First Name*" >
<div class="error"></div>
</div>
<div class="item">
<input type="text" placeholder="Last Name*">
<div class="error"></div>
</div>
<div class="item">
<input type="text" placeholder="Email Address*" class="email">
<div class="error"></div>
</div>
</div>
Instead of going through the process of checking for empty boxes, use the HTML boolean attribute required.
<input type="text" placeholder="First Name" required/>
That will make sure the user cannot submit until all required marked input fields are filled out.
Also, to validate an email, there is an input type for that too.
<input type="email" placeholder="Email Address" class="email"/>
For more info on the email input type, check out https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email.
Hope this was helpful to you.
Related
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 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;
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>
Here, In my code First name and Last name fields placed side by side how to write a validation for that 2 fields i tried but am not getting correct.I attached image and my code below
jQuery code:
jQuery(function(){
jQuery("#fName").validate({
expression: "if (VAL.match(/^[a-zA-Z]{2,30}$/)) return true; else return false;",
message: "Please enter the First Name Last Name"
});
});
signup.html
<div class="form-fullname">
<input class ="first-name"type="text" id="fName" name="firstname" placeholder="First name" required="">
<input class="last-name" type="text" id="lName" name="lastname" placeholder="Last name" required="">
</div>
The full page is an error image.
Error:
in this signup form when am entered numbers in first name it should show error message at below, but it is showing beside first name as shown in picture. So can you tell me how can i get error message in below.
Try to add the regex on input tag Instead:
<form action="register_page">
<div class="form-fullname">
<input class ="first-name" type="text" id="fName" name="firstname" placeholder="First name" pattern="^\w{2,30}$" required>
<input class="last-name" type="text" id="lName" name="lastname" placeholder="Last name" pattern="^\w{2,30}$" required>
</div>
<input type="submit" value="Register">
</form>
Note that you can use \w on regex instead of [a-zA-Z]. This way you don't need jquery validation in this case.
You can use test function on the regular expression in JavaScript to know whether the input is in valid format.
Use css function to display or hide the error messages.
If you want to show error for first name field when last name field is focused you can write an on focus event in jQuery.
$(document).ready(function () {
var NAME_REGEX = /^[a-zA-Z]{2,30}$/;
$('#signupBtn').click(signupBtnClick);
$('input[name="lastname"]').focus(lastNameOnFocus);
function signupBtnClick() {
validateFirstName();
validateLastName();
}
function lastNameOnFocus() {
validateFirstName();
}
function validateFirstName() {
var firstName = $('input[name="firstname"]').val();
if(NAME_REGEX.test(firstName)) {
$('#firstnameerror').css('display', 'none');
} else {
$('#firstnameerror').css('display', 'block');
}
}
function validateLastName () {
var lastName = $('input[name="lastname"]').val();
if(NAME_REGEX.test(lastName)) {
$('#lastnameerror').css('display', 'none');
} else {
$('#lastnameerror').css('display', 'block');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<h3>Sign Up</h3>
</div>
<div>
<input type="text" name="firstname" placeholder="First Name">
<span id="firstnameerror" style="color: red; display: none;">First Name is required</span>
</div>
<div style="margin-top: 1%;">
<input type="text" name="lastname" placeholder="Last Name">
<span id="lastnameerror" style="color: red; display: none;">Last Name is required</span>
</div>
<div style="margin-top: 2%;">
<button type="button" id="signupBtn">Submit</button>
</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;
});