I've been using JQuery validation for all of my forms on my website but I've just started on an upload script for image files and it's not validating correctly. Here is the code that I have:
$(document).ready(function()
{
var avatarok = 0;
//Post Avatar
$('#avatar').blur(function()
{
var avatar=$("#avatar").val();
if(avatar.length < 1){
avatarok = 0;
}
else{
avatarok = 1;
}
});
// Submit button action
$('#avatarButton').click(function()
{
if(avatarok == 1)
{
$('.avatarValidation').addClass("sending");
$("#avatarForm").submit();
}
else
{
$('.avatarValidation').addClass("validationError");
}
return false;
});
//End
});
When I click on the button (avatarButton) it always shows the error class, even if a file has been selected. Any theories?
check the below solution and blur condition not executing so that u are getting same message
// Submit button action
$('#avatarButton').click(function()
{
var avatar=$("#avatar").val();
if(avatar == 1)
{
$('.avatarValidation').addClass("sending");
$("#avatarForm").submit();
}
else
{
$('.avatarValidation').addClass("validationError");
}
return false;
});
//End
and remove your blur function no use
Related
I have a function to test and make sure at least one form field is filled out:
function checkFields(form) {
var checks_radios = form.find(':checkbox, :radio'),
inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]');
var checked = checks_radios.filter(':checked');
var filled = inputs.filter(function(){
return $.trim($(this).val()).length > 0;
});
if(checked.length + filled.length === 0) {
return false;
}
return true;
}
And that is called when the form is submitted:
$(function(){
$('.checkThisForm').on('submit',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
/* ??? */
}
});
});
What goes in my else { } to allow the form to submit if the user has supplied at least one element to search for in the form?
return for form action will indicate to proceed or stop the submission
$('.checkThisForm').on('submit',function(e){
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
return false;
}
return true;
});
you are required to follow below info. First you need to triger click event and submit
$(function(){
$('.checkThisForm').on('click',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
this.submit();
}
});
I need to create a re-useable function. The following script should prevent form submit and show a div alert. This version does not prevent form submit
<script type="text/javascript">
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
$(function() {
$('form#vendiendo').submit(function(e) {
if (Number($("#venta").val()) <
Number($("#costo").val())) {
$("#warnings").show();
//here start the new code I added
if (Number($("#cantidad").val()) >
Number($("#stock").val())) {
$("#warnings2").show();
//here ends the new code I added
return false;
}
});
});
</script>
If you want to stop the form from submitting in the case of an error, this should do.
<script type="text/javascript">
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
$(function() {
$('form#vendiendo').submit(function(e) {
if(Number($("#venta").val()) < Number($("#costo").val())) {
$("#warnings").show();
// You're still in the first if() statement. Is that what you want?
if (Number($("#cantidad").val()) > Number($("#stock").val())) {
// At this point, both checks have failed. We want to stop the
// default behavior.
e.preventDefault();
e.stopPropagation();
// And tell the user why we failed.
$("#warnings2").show();
return false;
}
});
});
</script>
I have a simple form with some form fields. Some of them are required some are not. The required field are required by adding the class 'required'.
When I submit I check the #contact-form fields and on the basis of there I give the empty field error classes and submit the form yes or no.
Adding the error classes to the fields is not a problem, but checking the "error" variable is. Because I don't know where I can check the error variable.
This is my jQuery code:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});
JsFiddle
The following code should do what you want, just give your contact form submit button the id of #contact-form-button.
$('#contact-form-button').click(function(e) { // using click function
// on contact form submit button
e.preventDefault(); // stop form from submitting right away
var error = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
error = true;
}
});
if (!error) { // if not any errors
$('#contact-form').submit(); // you submit form
}
});
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
return false;
}
return true;
})
if validation cross successfully then it return true for submit the form
I found out that my code just works. The reason I thought it was not working, is because I was still using PHP handling my real website where I made 1 field required and in my jQuery not. This made the confusion.
So the following code works:
$('#contact-form').submit(function (event) {
var errors = false;
$(this).find('.required').each(function () {
if ($(this).val().length < 1) {
$(this).addClass('error');
errors = true;
}
});
if (errors == true) {
event.preventDefault();
}
});
This is part of my jquery function that validades a form i have on my website:
/*
validates errors on all the fieldsets
records if the Form has errors in $('#formElem').data()
*/
function validateSteps(){
var FormErrors = false;
for(var i = 1; i < fieldsetCount; ++i){
var error = validateStep(i);
if(error == -1)
FormErrors = true;
}
$('#formElem').data('errors',FormErrors);
}
/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateStep(step){
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == ''){
hasError = true;
$this.css('background-color','#FFEDEF');
}
else
$this.css('background-color','#A8FC9C'); /* Campo preenchido */
});
var $link = $('#navigation_form li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError){
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
/*
if there are errors don't allow the user to submit
*/
$('#enviar_candidatura').bind('click',function(){
var preenchimentoForm=true;
if($('#formElem').data('errors')){
preenchimentoForm=false;
dadosFormularios(preenchimentoForm);
//return false;
}
else{
dadosFormularios(preenchimentoForm);
}
});
});
However, i'm using too LiveValidation (http://livevalidation.com/) to validade fields client-side. Obiously, if the part validated by jquery is Ok, doesn't matter if there's errors on the LiveValidation part because the form is submitted.
So, what i want is to add an if clause or something like that inside this jquery code to verify if there are LV_invalid_fields. If 'yes' then block form from submitting like it's done with the jquery validation part, but i don't know how to do it neither where is the right place in the code above to put this verification. I would appreciate some help. Thanks!
//... live validation codes here
$("#myform").submit( function (event) ) {
event.preventDefault();
if ($(".LV_invalid").length > 0) {
//do not submit
}
else {
//do form submission here
}
}
First, you have to change the binding on the click to a binding on the submit action on the form.
And your function must return false on the submit action to stop the submitting action.
So, change your code like this :
$('#formElem').submit( function (event) ) {
var preenchimentoForm = true;
if ($('#formElem').data('errors')){
preenchimentoForm = false;
}
return preenchimentoForm;
}
You can read some explications about unobtrusive javascript here.
There is an option in the LiveValidation library which is not explained in the documentation http://livevalidation.com/documentation
To prevent LiveValidation's submission while still keeping its validation events, you may use the "afterValidation" option.
Example:
var prevent = function (e) {
e.preventDefault();
};
var yourValidation = new LiveValidation(
"inputID", {
//Your other options
afterValidation: prevent
}
);
yourValidation.add( Validate.Presence, { your options } );
I want my validation control to be enable/disable with javascript. When I click on radiobutton list(yes/no), 2-3 rows becomes visible. Once Yes is clicked, then and only then user has to enter input for the textbox provided in that rows. For this I have kept require field validators. I am disabling all of them on page load and again enabling in javascript using ValidatorEnable(control, enable). But in this case, when ever I click on radio button list the rows becomes visible and at the same time validation control shows error message. I want error message to be seen on the submit button click only. Till then no message should appear.
How can I do so..?
Add code below right after ValidatorEnable(control, enable) method call:
if (control.style.visibility == "visible") {
control.style.visibility = "hidden";
} else {
control.style.display = "none";
}
function HasPageValidators() {
var hasValidators = false;
try {
if (Page_Validators.length > 0) {
hasValidators = true;
}
}
catch (error) {
}
return hasValidators;
}
function ValidationGroupEnable(validationGroupName, isEnable) {
if (HasPageValidators()) {
for (i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].validationGroup == validationGroupName) {
ValidatorEnable(Page_Validators[i], isEnable);
}
}
}
}
Then call:
ValidationGroupEnable('validationgroup', false);
i think it will help you....