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 } );
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 have a code that execute the submit event from the form and I want the modal stay open if the validation is false, but it doesn't work.
var myForm = document.updteform;
var condition = true;
if(myForm.pass1.value !== myForm.pass.value){
alert("Password Doesn't Match, Please try again.");
myForm.pass1.focus();
condition = false; //it will return the value
}
After that... this code below will execute.
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
This one works...
Step 1: create an onlick that calls the function to your JavaScript
Step 2: create a function:
function changePass(){
var oldpass = document.getElementById("password1").value;
var newpass = document.getElementById("password2").value;
if (oldpass != newpass) {
alert("Password Doesn't Match Please try again.");
return false; //the modal will not close because it doesn't return a value.
} else {
document.getElementById("form_id").action = "<?= base_url('index.php/Employee/updateUser'); ?>"; // Setting form action to your Controller page.
document.getElementById("form_id").submit(); // Submitting form
}
}
That say so.. Hopefully it'll help :)
I have this js code
$(document).ready(function(){
$("#frm_registration").submit(function(event){
var submit = false;
termsIsChecked = $("#user_terms_of_service").is(":checked");
uEmail = $("#user_email").val();
uPassword = $("#user_password").val();
uConfirmPassword = $("#user_password_confirmation").val();
uFirstName = $("#user_firstname").val();
uLastName = $("#user_firstname").val();
uContactNumber = $("#user_firstname").val();
uOtherInformation = $("#user_firstname").val();
// if(uPassword.length === 0){
// uPassword.after("<p>Password can't be blank</p>");
// submit = false;
// }
if(submit === false){
event.preventDefault();
}
});
});
if i uncomment the if block the form will submit event if i change event.preventDefault(); to return false; it still won't work if the if block is uncommented. my problem is why jquery is reponding like this, if i add if statement the preventDefault and return false; wont work but if i remove if statement or comment it out the preventDefault and return false; will work.can someone explain why its like this
The problem is uPassword is not a jQuery object, it is a string so there is no method called after for String object. Which should give you an error like Uncaught TypeError: uPassword.after is not a function in your browser console.
$("#user_password").after("<p>Password can't be blank</p>");
Also you will have to initialize submit with the value false like
$(document).ready(function () {
$("#frm_registration").submit(function (event) {
var submit = true;
termsIsChecked = $("#user_terms_of_service").is(":checked");
uEmail = $("#user_email").val();
uPassword = $("#user_password").val();
uConfirmPassword = $("#user_password_confirmation").val();
uFirstName = $("#user_firstname").val();
uLastName = $("#user_firstname").val();
uContactNumber = $("#user_firstname").val();
uOtherInformation = $("#user_firstname").val();
if (uPassword.length === 0) {
$("#user_password").after("<p>Password can't be blank</p>");
submit = false;
}
if (submit === false) {
event.preventDefault();
}
});
});
Demo: Fiddle
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();
}
});
I'm doing some jQuery form validation and I came up with an issue. I have the following code so far:
// catch any form submission
$('form').submit(function () {
'use strict';
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required) {
// catch any field that should be required
$(this).find('input[required]').each(function () {
// if is empty
if ($(this).val() === '') {
// create a span that contains a warning to the user
var requiredFieldWarning = document.createElement('span');
requiredFieldWarning.text = 'This field is required.';
// display the span next to the current field
}
});
}
});
I'm trying to "attach" or display a span next to any input of the submitted form that doesn't validate, but I don't know how to. I want to do this unobtrusively, that's why I create the said span inside JavaScript.
Also, how can I prevent the form from being submitted if any of the fields of the submitted form doesn't validate?
why reinvent the wheel? you should use the jquery form validation plugin..
edit: added code to prevent submition of invalid form.
to answer your question:
$('form').submit(function (e) {
'use strict';
var valid = true;
var $form = $(this);
$form.find("span.error").remove();
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required) {
// catch any field that should be required
$form.find(':input[required]').each(function () {
// if is empty
var $this = $(this);
if ($.trim($this.val()) === '') {
// create a span that contains a warning to the user
$this.after("<span class='error'>This field is required.</span>");
valid = false;
}
});
}
if(!valid){
e.preventDefault();
}
});
here is a shorter version:
$('form').submit(function (e) {
'use strict';
Modernizr.input.required ? e[$(this).find("span.error").remove().end()
.find(':input[required][value=""]')
.after("<span class='error'>This field is required.</span>")
.length ? 'preventDefault': 'isDefaultPrevented']() : null;
});
I am adding a span tag after the input. Before the form is revalidated it removes these spans and recreates only if needed. If any of these spans are added the form isn't submitted.
$('form').submit(function (event) {
'use strict';
$('.invalid-error', $(this)).remove();
// remove any old spans
var submit_form = true;
// form submits by default
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required) {
// catch any field that should be required
$(this).find('input[required]').each(function () {
// if is empty
if ($(this).val() === '') {
$(this).after('<span="invalid-error">This field is required.</span>');
// add span after input
submit_form = false;
}
});
}
if(!submit_form) event.preventDefault();
// stop form from submitting
});
jsFiddle ( http://jsfiddle.net/4KxzB/10/ )
Here is my working example, works as expected in chrome.
To stop the form from submitting, just return false;
<form>
<input type="text" required/>
<input type="submit" value="submit"/>
</form>
<script>
$('form').submit(function ()
{
'use strict';
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required)
{
var validInput = true;
// catch any field that should be required
$(this).find('input[required]').each(function ()
{
// if is empty
if ($(this).val() === '')
{
// create a span that contains a warning to the user
var requiredFieldWarning = document.createElement('span');
requiredFieldWarning.text = 'This field is required.';
// Cancels form submit
validInput = false;
}
});
return validInput;
}
});
</script>
var flag = 0;
if ($(this).val() === '') {
flag = 1;
var warningblock = '<span class="warning">This field is required.</span>';
$(this).after(warningblock);
}
//end of each loop
if(flag){ //put this block out side the loop
return false; //form wont submit
}
return true;
CSS
.warning{
/**add styles for warning here***/
}