Form validation jQuery AJAX [closed] - javascript

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

Related

error classes do not show up when form is submitted

I'm trying to validate my signup form using JavaScript. I submit the form and the default action is prevented but none of my error handler classes show up, nor do I get any errors in my error log. if anyone can show me what I'm doing wrong, it would greatly appreciated. I'm trying to show a red background on the input fields if the user doesn't fill in the input.
$(document).ready(function () {
$("#signupForm").submit(function (e) {
removeFeedback();
var errors = validateSignup();
if (errors == "") {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
});
function validateSignup() {
var errorFields = new Array();
//Check required fields to see if they have anything in them
if ($('#signupFirst').val() == "") {
errorFields.push('first');
}
if ($('#signupLast').val() == "") {
errorFields.push('last');
}
if ($('#signupEmail').val() == "") {
errorFields.push('email');
}
if ($('#signupPassword').val() == "") {
errorFields.push('pwd');
}
if (!($('#signupEmail').val().indexOf(".") > 2) && ($('#signupEmail').val().indexOf("#"))) {
errorFields.push('email');
}
return errorFields();
}
function provideFeedback(errorFields) {
for (var i = 0; i < errorFields.length; i++) {
$("#" + errorFields[i]).addClass("inputError");
$("#" + errorFields[i] + "Error").removeClass("errorFeedback");
}
}
function removeFeedBack() {
$('input').each(function () {
$(this).removeClass("inputError");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="index-bg-wrapper">
<div class="main-signup-container">
<form id="signupForm" class="signup-form" action='include/signup.inc.php' method='POST'>
<input id="signupFirst" type="text" name="first" placeholder="First Name">
<input id="signupLast" type="text" name="last" placeholder="Last Name">
<input id="signupEmail" type="text" name="email" placeholder="Email">
<input id="signupPassword" type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Signup</button>
</form>
</div>
</div>
</body>
This is not ok:
return errorFields(); // Here you're trying to call a function with an array.
Just return the array: return errorFields;
Another problem is the comparison:
if (errors == "") { // This is not ok (it's always false), so, what you want to check is the length of errors.
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
So, check for the length:
if (errors.length === 0) {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
Here you go buddy, I have fixed multiple errors though very minor in your code but its working fine now.
Plnkr:
http://embed.plnkr.co/MaUzZh1zUFBL4y8qAf6n/
You were pushing wrong name inside the errorFields array.
Due to wrong field name and DOM id mismatch jquery couldn't find the element and apply the class.
I hope you can compare and get this code working.

jQuery validation is not working in contact form

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

repeat checking of form data without submit (JavaScript, HTML, JQuery)

I'm trying to submit a HTML form, only when all the fields do not return false in the Javascript code.
My HTML looks like this, for simplicity I have just kept the name and email
<form method="post" action="RegistrationServlet" class="iform"
onsubmit="return sendForm();">
<ul><li><label for="YourName">*Your Name <span id="regNameErr"></span></label>
<input class="itext" type="text" name="YourName" id="YourName" /></li>
<li><br /><label for="YourEmail">*Your Email <span id="regEmailErr"></span></label>
<input class="itext" type="text" name="YourEmail" id="YourEmail" /></li>
<li><input type="submit" value="Submit" class="ibutton" name="SendaMessage"
id="SendaMessage" value="Send a Message!" readonly="readonly" /></li></ul></form>
The Javascript looks like this, again for simplicity I am just checking 2 fields:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.sendForm = function() {
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
$("#YourName").addClass("required");
window.scroll(0, 190);
$("#regNameErr").text("required");
return false;
}
if ($("#YourEmail").val() == "") {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
if (!isEmailValid($("#YourEmail").val())) {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Why is the sendForm() function not repeatedly being called to check that all fields are correct before submitting. Any ideas?
Also I understand that I can add a bounty after 2 days but I am not seeing any button on the editor.
Can you help?
sendForm is called only once per submit - this how it works, and there is no reason to call it multiple times.
If you want to have all your fields checked on submit - you should not return after each check. Instead you should postpone this action until the all fields are verified, and introduce some flag to remember results:
function() {
var formValid = true;
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
...
formValid = false;
}
if ($("#YourEmail").val() == "") {
...
formValid = false;
}
if (!isEmailValid($("#YourEmail").val())) {
...
formValid = false;
}
if (!formValid) {
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Side note. Have you considered any jQuery validation plugins for this? Might save you some implementation and maintenance efforts.

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

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