Validate form using jQuery - javascript

When a form submit button is clicked, a function to validate all the field is to be called. Nothing is to happen, however, if the validation fails.
I am using mailto: as my action, does this make a difference?
I would like to get clarification on two things:
Is this the correct way to call a function when clicking the submit button?
$(document).ready(function(){
$('#contactForm').submit(function(){
checkMail();
});
});
Can I still validate the fields even though I'm using mailto:?
Here is the rest of the code:
function checkEmail(){
var email = document.contact.email.value;
if(email == "") {
document.getElemtById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
HTML:
<form name="contact" action="mailto:exampleemail#hotmail.com" method="post">
<li>
<label for="email">Email</label>
<input id="email" type="text" name="email" placeholder="Enter Email Address">
</li>
<span id="email_error"></span>
Further, I don't get an error message on clicking submit.

No, you need the event handler to return false in case the validation failed. This will prevent the action from being executed, i.e. the mail program from being launched.
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
Source
Modify it like this:
$(document).ready(function(){
$('#contactForm').submit(function(){
return validate();
});
});
Of course, this implies that the validate() function needs to actually return false in case the validation fails, and true otherwise.
Further you are missing id="contactForm" on your <form> tag.
Also, you need to grab the email value correctly:
var email = $("#email").val();
There's another mistake: You misspelled getElementById(). Here's a corrected version:
function checkEmail() {
var email = $("#email").val();
if (email == "") {
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
Or alternatively, using all jQuery:
function checkEmail() {
var email = $("#email").val();
var $error = $("#email_error");
if (email == "") {
$error.html("No Email Address");
return false;
}
else {
$error.html("");
return true;
}
}

Here's what you need:
$(document).ready(function(){
$('#contactForm').submit(function(){
if (!validate()) {
return false; // Prevent the submit
}
});
});

For validating the fields of your form, before sending it, you can use the jQuery's validation plugin:
$(document).ready(function(){
$("#contactForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
});
Check the online doc for more information and examples: http://docs.jquery.com/Plugins/Validation#Validate_forms_like_you.27ve_never_been_validating_before.21

Related

Return False with Alert upon webflow form submission

I am trying to write a JS function which blocks users from submitting a personal email. Here is the code. When I remove the "alert" line, the user is blocked from a successful form submission. But there is no alert that prompts them to enter a business email.
$("form").submit(function(){
// Get the email value from the input with an id="Email-2"
var email_addr = $('#Email-2').val();
// The regex to check it against
var re = '[a-zA-Z_\\.-]+#((hotmail)|(yahoo)|(gmail))\\.[a-z]{2,4}';
// Check if the email matches
if(email_addr.match(re)){
// Email is on the filter list
// Return false and don't submit the form, or do whatever
window.alert("Enter Business Email");
return false;
} else {
// Email ok
// Allow the form to be submitted
return true;
}});
Below is where there error is occuring. I'm new to Javascript so it very likely could be a syntax issue.
window.alert("Enter Business Email");
return false;
I found a solution that worked, changed the code to the following:
$('#wf-form-Book-Demo-Form').submit(function(){
var email = $('#Email-2').val();
var reg = /^([\w-\.]+#(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)([\w-]+\.)+[\w-]{2,4})?$/;
if (reg.test(email)){
return 0;
}
else{
alert('Please Enter Business Email Address');
return false;
}
});

Cancelling a form submission, then submitting it again

So I have a login form. What I want I am currently doing is submitting the form using action="" etc.. with an onSubmit even with my form validation inside the javascript function validate(). Currently though it will submit the form and validate at the same time. What I want to happen is for it to not submit the form, or to cancel it as soon as we get into the validate function. And then if the forms are valid, submit the form.
This is my logic behind what I want to do
function validate() {
stopFormSubmit();
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
submitForm();
} else {
displayErrors();
}
}
My form looks like this
<form onSubmit="validate()" name="basicForm" id="basicForm" class="basicForm" action="login.php" method="post" autocomplete="off">
Is there anyway to do this?
The form does validate and then submit. Validation just takes very little time.
What you really want to do is to stop the form if it fails validation.
Using intrinsic event attributes, return false to stop the form being submitted. Since that is determined by the success of the validation, you need to return true or false from validate and then return that from your event handler.
onSubmit="return validate()"
and
function validate() {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
return true;
} else {
displayErrors();
return false;
}
}
Modern code would use unobtrusive JavaScript and bind the event handlers programatically. Then it would use the Event object to control that happened to the default behaviour. Since you are already using jQuery, we can use that to perform the event binding.
Remove the onsubmit attribute entirely.
jQuery('form').on('submit', validate); // Run this after the form exists in the DOM
and
function validate(evt) {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
// Do nothing
} else {
displayErrors();
evt.preventDefault();
}
}
I suggest to use jQuery Validation plugin, if possible.
Another idea - to do like here:
1. onSubmit="return validate()"
2. Update function:
function validate() {
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != "") {
submitForm();
// or you can simply return true to allow form data submitting
} else {
displayErrors();
return false;
}
}

Alert problems with mail checking script

In my short script, that is checking if submited email is in the right form, I always recive alert, no matter what I put in the form (email)
function checkEmail() {
var mail = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(mail.value))
{
alert('Prosimo, vnesite veljaven email');
mail.focus;
return false;
}
}

Form shows mistakenly the success alert box when it has invalid input in jQuery

In the script below I check if the email entered is valid. It is not the best regex but it is ok for now. Also for the moment I do not make any server side check for input. Only with this script.
I have this problem though:
When an email is valid, and after I type an invalid email I get first the Your email is not in valid format and then You will be notified when we launch. Thank you! alert. Also the email is sent. How to fix this ?
Thank you
this is my form
<form id="myform" action="" method="POST">
<input id="subscribe" name="subscribe" class="subscribe floatLeft" type="text">
<button id="signUp" class="signUp floatRight" ><intro>notify!</intro></button>
<div class="clear"> </div>
</form>
and here is the script
var signUp = function(inputEmail) {
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(inputEmail)) {
isValid = false;
alert('Your email is not in valid format');
}
$("#myform").submit(function(event) {
event.preventDefault();
if (!isValid) {
return false;
} else {
$.post('mailme.php', $("#myform").serialize(), function(data) {
alert('You will be notified when we launch. Thank you!');
});
return false;
}
});
};
You need the onsubmit event to return false;
You need to bind the submit event anyway and make the isValid check there;
$("#myform").submit(function(event){
event.preventDefault();
if(!isValid){
return false;
}else{
$.post(...)
return false;
}
});
--Edit--
Forgot to return false/event.preventDefault; But like i said, the submit event need to be bound anyway
--Edit2--
function validEmail(email){
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email.test(emailReg)
}
$(document).ready(function(){
$("#myform").bind({
submit: function(e){
e.preventDefault();
if(validEmail($("#myform").find("#subscribe").val()){
$.post(...)
alert("You will be notified");
return false;
}
else {
alert("Invalid email");
return false;
}
});
});
}
You need to return false or event.preventDefault() in the emailReg test.

Form submission will not stop for validation

What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either
$('#submit').click(function() {
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return false; // cancel form submission if email invalid
}
return false; // return true if no errors once i get it working
});
Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
// now that document is "ready"
$('#formId').submit(function() {
var email = $('#emailInput').val();
alert(email);
if(email.indexOf("#") == -1){
alert("invalid!");
return false; // cancel form submission if email invalid
}
alert("valid!");
return true; // return true if no errors once i get it working
});
});
Try wrapping your code in a ready block.
$(document).ready(function(){
// your code here
});
You should also be using the submit event on the <form> element, I think.
This is going to work. If you don't understand why, feel free to ask :)
var validated = false;
$(document).ready(function(){
$("#rfq").submit(function(event) {
if (validated === true) {
return true;
}
event.preventDefault(); // prevent submission
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return;
}
validated = true;
return $(this).trigger('submit');
});
});
You could try using this function to validate your address.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
And then modify your code to submit the form.
$('#submit').click(function() {
var email = $('#email').val();
if(!validateEmail(email)){
$("#email").addClass('invalid');
}
else {
$("form").submit();
}
});

Categories

Resources