I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>
Related
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 trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />
Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:
If error is found change text field background color to red, change field value to error message
If no errors are found, proceed
My problem
The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?
Code follows:
function validate(){
//form validation
var name=document.getElementById("name");
var surname=document.getElementById('surname');
//name
if (name.value=='') {
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name is required"
return false;
}
else if(isNaN(name)==true){
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name: Only enter letters A-Z"
return false;
}
//surname
if (surname.value == ""){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname is required"
return false;
}
else if(isNaN(name)==true){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname: Only enter letters A-Z"
return false;
}
return true;
}
HTML
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" id="name" value="Name" class="textbox" name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
<br />
<input type="text" id="surname" value="Surname" class="textbox" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number
isNaN(name.value)
Demo: Fiddle
You should use onsubmit event of form instead of click.
<form id="enquire" method="post" onsubmit="return validate()">
I am trying to build a website with a webform. I am using Godaddy's default webform PHP and I am not sure how to validate the form for required fields.
I want the user to not be able to submit the form prior to validation. I found JavaScript files online submitted by other users that address this problem but I can not seem to get it to work.
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
if (email.indexOf('#') == -1) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Below is the form:
<form onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10">
</textarea><br>
<input type="submit" name="submit" value="submit"/> <span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/> <input type="hidden" name="form_delivery" value="daily"/> <input type="hidden" name="form_format" value="html"/>
I tried submitting without entering anything and it redirects me to the thank you.
form is not defined in the function. There are several ways to handle this. The simplest would be to change return checkForm() to return checkForm(this) and
function checkForm(form) {
In the form, change checkForm() to checkForm(this). Then, in your javascript, change function checkForm() { to function checkForm(form) {
Maybe this will help.
You forgot 2 thing:
first, please add name="form" into
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
second, you misstake close form, please add this code to end of HTML
</form>
Your HTML will look like:
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10"></textarea><br>
<input type="submit" name="submit" value="submit"/>
<span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/>
<input type="hidden" name="form_delivery" value="daily"/>
<input type="hidden" name="form_format" value="html"/>
</form>
1 other thing is in javascript, function to check email address is incorrect, Correct is:
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
// incorrect email address
}
New script will be:
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Goodluck!