I have a form where I am using dropzone.js for file upload. Now I am validating all the input fields. But i'm not able to validate the file before submission. If the file is uploaded, then the submission should work. Otherwise it should throw an error like - "please upload the file". How can i achieve this?
HTML code:
<form action="/action">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" required>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<textarea class="form-control" id="message" name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="form-row">
<div id="resume" class="dropzone form-control"></div>
</div>
<input type="submit" class="btn btn-primary mt-10" id="item-submit" value="submit">
</form>
Javascript :
<script type="text/javascript">
$(document).ready(function () {
$("div#resume").dropzone({ url: "/change-this-later" });
var dropzone3;
Dropzone.autoDiscover = false;
dropzone3 = new Dropzone('#resume', {
maxFiles: 1,
});
$('#item-submit').click(function(e) {
e.preventDefault();
e.stopPropagation();
if ($('form#resume').valid()) {};
});
});
</script>
You can add a callback event which is called if the upload is successful
//indicates file upload is complete and is successful
var uploaded = false;
$("div#resume").dropzone({
url: "/change-this-later",
success: function (file, response) {
uploaded = true;
}
});
//Check the value of 'uploaded' when validating rest of fields
So I come around this. Since I submit all my images and fields in the same button, I just acceded to the files array in side the dropzone and validate that it's lenght wasn't 0. $animalImage is my dropzone.
var validateImages = function (animal) {
if ($animalImage.files.length == 0) {
swal({
title: 'Advertencia',
type: 'info',
html: "Debe de guardar al menos una imágen",
showCloseButton: true,
focusConfirm: false
});
return false;
}
return animal;
};
Hope it helps, side note a submit trough ajax so I just used dropzone for the user experience.
Related
I have a simple form with Ajax call, but ajax call gets executed even if form is not validated.
In below code line console.log("This line should execute only if Form is validated"); gets executed when form is not validate.
Bootstrap 5 validation Codepen code
(function () {
"use strict";
const forms = document.querySelectorAll(".requires-validation");
Array.from(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
else
{
console.log("This line should execute only if Form is validated");
// Call Ajax Function
// AjaxCallSaveData();
}
form.classList.add("was-validated");
},
false
);
});
})();
//$(document).ready(function () {
function AjaxCallSaveData()
{
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
superheroAlias: $("#superheroAlias").val()
};
$.ajax({
type: "POST",
url: "SubmitFORM.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
}
//});
Not sure if i am doing it right?
HTML
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<h3>Register you interest</h3>
<p>Fill in the data below, we will get back to you!</p>
<form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" id="name" placeholder="Full Name" required>
<div class="valid-feedback">Username field is valid!</div>
<div class="invalid-feedback">Username field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input class="form-control" type="email" name="email" id="email" placeholder="E-mail Address" required>
<div class="valid-feedback">Email field is valid!</div>
<div class="invalid-feedback">Email field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
event.preventDefault() will only stop the form from submitting. It cannot stop next lines of the JavaScript function from executing.
You should use return in place of event.preventDefault().
I am using the bootstrap 'needs-validation' for checking the validation form. Here when I click the submit button its validating the field and form is also getting submitted. What I want is when the validation fails the form should not get submitted. I found the form validation from (needs validation) from here https://www.w3schools.com/bootstrap4/bootstrap_forms.asp and I used it in my program.
My script is
<div class="row top-space-30">
<form class="needs-validation" novalidate action="" method="">
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="studentname">Student Name:</label>
<div class="col-md-6">
<input id="role" name="studentname" type="text" placeholder="name" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="department">Department:</label>
<div class="col-md-8">
<input class="form-control" type="text" id="department">
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
<script>
// Disable form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
$("#submit").click(function (e) {
var studentName = $("#role").val();
var departmentsList = $("#department").val().split(',');
$.ajax({
type: 'POST',
url: '/students/add',
data: {
'role': studentName,
'departmentslist': JSON.stringify(departmentsList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
})
</script>
Try this one, I have one function for validationsformSubmit add your own validations in that function.
<div class="row top-space-30">
<form class="needs-validation" name="myForm" action="" method="" onsubmit=" return formSubmit()" >
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="studentname">Student Name:</label>
<div class="col-md-6">
<input id="role" name="studentname" type="text" placeholder="name" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="department">Department:</label>
<div class="col-md-8">
<input class="form-control" type="text" name = "departmentname" id="department">
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="Submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
//Disable form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
function formSubmit(){
var forms = document.forms["myForm"];
var studenName = forms.studentname.value;
var departmentName = forms.departmentname.value;
// perform validation for studentname and departname if they are validated then return true, else for wrong input return false
if(isNaN(studentname) && isNaN(departmentname)){
return true;
}
else{
return false;
}
}
$("#submit").click(function (e) {
var studentName = $("#role").val();
var departmentsList = $("#department").val().split(',');
$.ajax({
type: 'POST',
url: '/students/add',
data: {
'role': studentName,
'departmentslist': JSON.stringify(departmentsList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
})
</script>
I am implementing Google's Invisible Recaptcha and I am trying to have everything run from my mail.js file (and I would really prefer to keep it there). For some reason Recaptcha is not finding "onSuccess" in mail.js but if I move it to the HTML inside <script></script> it works.
I am getting this error in JavaScript console: ReCAPTCHA couldn't find user-provided function: onSuccess when it is in mail.js
$(".input-field").each(function () {
var $this = $(this);
if ($this.val().length) {
$this.parent().addClass("input--filled")
}
$this.on("focus", function () {
$this.parent().addClass("input--filled");
});
$this.on("blur", function () {
if (!$this.val().length) {
$this.parent().removeClass("input--filled")
}
})
});
$(function () {
// Get the form.
var form = $('#ajax-contact'),
// Get the messages div.
formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function (e) {
// Stop the browser from submitting the form.
grecaptcha.execute();
e.preventDefault();
});
});
var onSuccess = function(response) {
$("#btn-submit").addClass("btn-loading");
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function (response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success').fadeIn().delay(5000).fadeOut();
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$(form).trigger("reset");
grecaptcha.reset();
$("#btn-submit").removeClass("btn-loading");
})
.fail(function (data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error').fadeIn().delay(5000).fadeOut();
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
$("#btn-submit").removeClass("btn-loading");
});
};
here is the HTML:
<form id="ajax-contact" class="" method="post" action="mailer.php">
<fieldset>
<div class="row">
<div class="input col-xs-12 col-sm-12 padding-bottom-xs-50 padding-bottom-40">
<label class="input-label" for="name">
<span class="input-label-content font-second" data-content="name">name *</span>
</label>
<input class="input-field" type="text" name="name" id="name" required />
</div>
<div class="input col-xs-12 col-sm-6 padding-bottom-xs-50 padding-bottom-50">
<label class="input-label" for="email">
<span class="input-label-content font-second" data-content="email">email *</span>
</label>
<input class="input-field" type="email" name="email" id="email" required />
</div>
<div class="input col-xs-12 col-sm-6 padding-bottom-xs-60 padding-bottom-50">
<label class="input-label" for="company">
<span class="input-label-content font-second" data-content="company">company</span>
</label>
<input class="input-field" type="text" name="company" id="company" />
</div>
<div class="message col-xs-12 col-sm-12 padding-bottom-xs-40 padding-bottom-30">
<label class="textarea-label font-second" for="message">message *</label>
<textarea class="input-field textarea" name="message" id="message" required></textarea>
</div>
</div>
<div class="g-recaptcha" data-sitekey="6Lf-6XQUAAAAAGhsZxXTlA3MtMGr_xDhOXPG-Ds0" data-badge="inline" data-size="invisible" data-callback="onSuccess"></div>
<div id="form-messages" class="form-message"></div>
<div class="col-xs-12 margin-top-30 text-center">
<button id="btn-submit" type="submit" class="btn btn-animated btn-contact ripple-alone" data-text="send it"><span class="btn-icon"><span class="loader-parent"><span class="loader3"></span></span>
</span>
</button>
</div>
</fieldset>
I am trying to make an AJAX request when submitting a form, but I cannot even see the request in the Network panel because it fails before hitting the URL. This is the code:
// contact form
$(function() {
$(document).on("submit", "#contact-form", function(e) {
// prevents normal submit
e.preventDefault();
var form = $(this);
var url = form.attr("action");
$.post(url, function(data) {
alert(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown); // TypeError: Cannot read property 'count' of undefined
});
});
})
And this is the HTML:
This is the HTML:
<form name="contact" method="post" action="/app_dev.php/contacts/submit" id="contact-form">
<div class="row">
<div class="col-xl-6 form-group">
<input type="text" id="contact_firstname" name="contact[firstname]" maxlength="255" class="form-control form-control-lg" placeholder="Entre ton nom*" />
</div>
<div class="col-xl-6 form-group">
<input type="text" id="contact_lastname" name="contact[lastname]" required="required" maxlength="255" class="form-control form-control-lg" placeholder="Entre ton nom de famille*" />
</div>
<div class="col-xl-6 form-group">
<input type="email" id="contact_email" name="contact[email]" required="required" maxlength="255" class="form-control form-control-lg" placeholder="Entre ton adresse e-mail*" />
</div>
<div class="col-xl-6 form-group">
<input type="text" id="contact_subject" name="contact[subject]" required="required" maxlength="255" class="form-control form-control-lg" placeholder="Entre le sujet*" />
</div>
<div class="col-12 mb-5">
<textarea id="contact_message" name="contact[message]" required="required" class="form-control" rows="3" placeholder="Écris ton message*"></textarea>
</div>
<input type="hidden" name="_csrf_token" value="Su1QsqB8LZdqqVRxrxBPeXQNpp29QlYEt7yvg13hzCI">
<div class="col-xl-3">
<button type="submit" class="btn btn-xl btn-block">Envoyer</button>
</div>
</div>
</form>
I always receive an alert with this message: TypeError: Cannot read property 'count' of undefined.
If I try to put the same code outside of the submit (in the document ready event) it works fine:
// contact form
$(function() {
//$(document).on("submit", "#contact-form", function(e) {
//// prevents normal submit
//e.preventDefault();
//});
var form = $("contact-form");
var url = form.attr("action");
$.post(url, function(data) {
alert(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown); // WORKS FINE
});
})
These are my JavaScript files:
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/js/app.js"></script>
I seems that it was a very odd bug caused by the Symfony Web Profiler Toolbar! Luckily a fix has been released 13 hours ago:
https://github.com/symfony/symfony/releases/tag/v2.8.36
This is the issue:
https://github.com/symfony/symfony/pull/26368
Form is not cleared after saved record in angularJs. I'm trying to reset form many ways, but form is not reset.
My angularjs version is 1.4.8.
This question is also a duplicate, but I tried what stack overflow users said. That has not worked for me.
Looking for a positive reply
Thank you.
Html code:
<form name="myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue"
id="forumValue" placeholder="fourm Id" />
<div class="form-group row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="answer" class="form-control"
ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success"
ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
Controller Code:
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};
Is your form wrapped in an ng-if statement? If so, the form might be inside a child scope, and you might try:
Option A
Replace your ng-if with an ng-hide.
Option B
Bind the form to an existing object on the parent scope:
$scope.myData = {};
$scope.saveUserAnswer = function(fid) {
...
};
Then in your HTML, refer to the form on the parent scope:
<form name="myData.myForm" id="myForm" novalidate>
</form>
Source: https://github.com/angular/angular.js/issues/15615
I have attempted to recreate your problem but without the call to the UserRepository just to confirm that we can set the form $pristine value to true and to reset the form.
<form name="form.myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue" id="forumValue" placeholder="fourm Id" />
<div class="form-grou`enter code here`p row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="form.myForm.answer" class="form-control" ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success" ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
<pre>{{form.myForm.$pristine}}</pre>
and the controller code like so :
$scope.form = {};
$scope.saveUserAnswer = function(fid) {
$scope.form.myForm.$setPristine();
$scope.fid = {};
//omitted the user repository code
};
The above will set the pristine value of the form to true and also reset the value of fid on click of the button.
EDIT
Also the call to your repository function should be in this format:
UserRepository.saveUserAnswer(fid).then(
function(response){
//success
},
function(response){
//error
}
);
In controller try to add '$scope.fid.answer=null;' after scope.myForm.$setPristine();
like this.
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.fid.answer=null;
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};