jQuery validation is not working in contact form - javascript

I want validation through jQuery. I have two fields name and email. email blank field validation is not working.
Here is my code,
<form>
Name : <input type="text" name="name" id="name"><br>
<span id="nameSpan"></span>
<br>
Email:<input type="email" name="email" id="email1"><br>
<span id="emailSpan"></span>
<br>
<input type="submit" id="submitBtn">
</form>
javascript
$(document).ready(function(){
var name = $("#name").val();
var email1 = $("#email1").val();
$("#submitBtn").on("click", function(){
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Please guide me where am I wrong. Thanks in advance

You are checking values of inputs only once while page load. We need to check them everytime so lets move this part into onclick function.
$(document).ready(function(){
$("#submitBtn").on("click", function(){
var name = $("#name").val();
var email1 = $("#email1").val();
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});

Related

Triggoring Form focus with logic to another field [duplicate]

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

Javascript multiple fields validating

First, I have to validate that id and password textboxes are not empty(That one's working). Then I have to validate on the same form that id on textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work). Any ideas on what's wrong with my code?
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID;
custID = document.getElementsByName("idtb").valueOf();
if (custID !== isNan) {
alert("Customer ID needs to be numeric");
return false;
}
if (custID < 3000) {
alert("ID must be above 3000");
return false;
}
if (custID > 3999) {
alert("ID must be below 3999");
return false;
}
}
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID = document.getElementById('idtb').value;
if (Number.isNaN(parseInt(custID))) {
alert("Customer ID needs to be numeric");
return false;
}
if (parseInt(custID) < 3000) {
alert("ID must be above 3000");
return false;
}
if (parseInt(custID) > 3999) {
alert("ID must be below 3999");
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form action="#" onsubmit="return validatefunctions()" method="post">
Customer ID: <input type="text" name="idtb" id="idtb"><br /><br />
Password: <input type="text" name="pwtb" id="pwtb"><br /><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work)
Why don't use input type number specifying the min and max attribute:
<form>
<input type="number" name="quantity" min="3000" max="3999" value="3000">
<input type="submit">
</form>

jQuery form validation ( if == "" do this) only works on first input

I have a form which I'm using jQuery to validate that the inputs aren't empty. (I'm using bootstrap too)
<form action="" method="post">
<div id="name_input" class="form-group">
<input id="name" type="text" name="name" placeholder="Name">
<span class="glyphicon glyphicon-remove form-control-feedback name_span></span>
</div>
<div id="email_input" class="form-group">
<input id="email" type="email" name="email" placeholder="Email">
<span class="glyphicon glyphicon-remove form-control-feedback email_span></span>
</div>
<input type="submit" name="submit" value="save">
</form>
with jQuery
$(document).ready(function() {
$('.form-control-feedback').hide();
$(".submit").click(function() {
var name = $("#name").val();
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
return false;
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
return false;
}
});
});
when I use this code and both inputs are empty, the classes "has-error" and "has-feedback" only append to the first input.
if the first input is filled in and the second is empty the classes adds to the second one, and if I empty the first one too that one also get the classes.
but if I do the other way around, so the first is empty first and the secound input is empty after, the classes still only add to the first one.
Also when I fill one of them in, I want to removeClass but I can't do that with:
} else {
$("#name_input").removeClass("has-error has-feedback");
$(".name_span").hide();
}
since that will submit the form and obvious I can't add return false; since that will prevent the form to process even if it's filled in... Any suggestions on these?
A return statement immediately stops executing a function. So this code here
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
return false;
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
return false;
}
Says that if name == "" , don't even evaluate the email. Instead, you may want to use a flag to see if any errors occurred.
var dataIsValid = true;
var name = $("#name").val();
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
dataIsValid = false;
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
dataIsValid = false;
}
return dataIsValid;
As #imvain2 pointed out, you'll also want to remove the error classes. Otherwise, as soon as you get an error once, it will always look like they have an error.
var dataIsValid = true;
var name = $("#name").val();
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
dataIsValid = false;
} else { // Valid, remove the error classes
$("#name_input").removeClass("has-error has-feedback");
$(".name_span").hide();
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
dataIsValid = false;
} else { // Valid, remove the error classes
$("#email_input").removeClass("has-error has-feedback");
$(".email_span").hide();
}
return dataIsValid;
You are returning on the first error. If you want to list through each you need to remove the individual return statements.
$(document).ready(function() {
$('.form-control-feedback').hide();
$(".submit").click(function() {
var name = $("#name").val(),
errorMsg = [];
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
errorMsg.push('Invalid Name');
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
errorMsg.push('Invalid Email');
}
if (errorMsg.length > 0 ){
// alert('Errors:\n' + errMsg.join('\n'));
return false;
}
});
});

Form validation jQuery AJAX [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to made a simple contact form validaton. I´m newbie in Javascript. I tried many tutorials for newbies, hovever, no one tutorial solved my situation, so I´m trying to made my own JS.
But it have two issues:
Form is sent though is empty, although incorrect validation
If validation is failed, it should return all errors on same time
$("#submit").click(function () {
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
function validate() {
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
return false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
return false;
}
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,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
return false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
return false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
return false;
}
return (true);
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form autocomplete="off" id="contact-form" method="post" enctype="multipart/form-data" action="modules/process.php">
<div class="group">
<input type="text" class="move" name="f1" id="f1" /><span class="error" id="f1Err"></span>
<label>Name</label>
</div>
<div class="group">
<input type="text" class="move" name="f2" id="f2" /><span class="error" id="f2Err"></span>
<label>E-mail</label>
</div>
<div class="group">
<input type="text" class="move" name="f3" id="f3" /><span class="error" id="f3Err"></span>
<label>Message subject</label>
</div>
<div class="group">
<textarea type="text" class="move" name="f4" id="f4"></textarea><span class="error" id="f4Err"></span>
<label>Message</label>
</div>
<div class="submit-btn">
<input type="submit" value="SUBMIT" id="submit">
</div>
</form>
Thanks for any ideas.
Lets start with the first click function and the submit functionality, you haven't preventedDefault() to prevent the default method of the submit input you have provided, so you would need to preventDefault() of the event that is being sent in like so
$("#submit").click(function (e) {
e.preventDefault();
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
as the method name shows, its "preventing the default behavior" from running. Next in your validation method, you are returing false after checking a field, so once that one of the validations fails, you are returning. maybe you should return a flag instead so like:
function validate() {
var flag = true;
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
flag = false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
flag = false;
}
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,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
flag = false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
flag = false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
flag = false;
}
return flag;
}
I think should solve your two biggest issues that you pointed out were wrong. (this is not necessarily the best implementation and variable names, i'll leave you to learn and improve on it)
I made a fiddle http://jsfiddle.net/3dnkvtb1. I set errors to false before validating each input, then for each check I set error to true if empty. Make sure to check the console for errors as you go. I added a console.log for each check. Then if no errors, send and clear your form.
$("#submit").click(function(event) {
event.preventDefault();
var hasError = false;
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,}))$/igm;
if ($("#f1").val() == "") {
hasError = true;
$("#f1Err").html("Name is required");
}
console.log($("#f1").val());
if ($("#f2").val() == "") {
hasError = true;
$("#f2Err").html("E-mail is required");
}
console.log($("#f2").val());
if (!re.test($("#f2").val())) {
hasError = true;
$("#f2Err").html("Incorrect e-mail format");
}
console.log($("#f3").val());
if ($("#f3").val() == "") {
hasError = true;
$("#f3Err").html("Message subject is required");
}
console.log($("#f3").val());
if ($("#f4").val() == "") {
hasError = true;
$("#f4Err").html("Message is required");
}
console.log($("#f4").val());
if(!hasError){
console.log('no errors');
//send your form
$.ajax({
url: 'url-here',
type: 'post',
dataType: 'json',
action : 'submit',
data: $('#contact-form').serialize(),
success: function(response) {
console.log(response);
//do something
clear();
}
});
} else {
console.log('something is up');
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
});

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

Categories