I want to submit my form when .valid returns true. It works fine with login_form, but it is returning true for signup_form. The .validate methods work fine, but when the form is not validated, .valid returns true for signup_form.
var login_form = $( "#login_form" );
var signup_form = $( "#signup_form" );
login_form.validate();
signup_form.validate({
rules:
{
signup_repeat_password:
{
equalTo:"#signup_password"
}
},
messages:
{
signup_repeat_password:
{
equalTo:"Please repeat the password"
}
}
});
if ( login_form.valid())
{
login_form.submit(
function()
{
alert("Please submit login_form");
}
);
}
if ( signup_form.valid())
{
signup_form.submit(
function()
{
alert("Please submit signup_form");
}
);
}
Related
despite my problem is similar with this
the proposed solution did not work for me.
Let me explain what happens.
As the title suggests unhiglight is called right after highlight.
and this happens only under one scenario only:
using remote method of email.
If the ajax call returns true(after hitting the submit button)(email does not exist) error class is added and immediately replaced by valid class in the fields that are not filled(required)...
if I hit submit again the problem does not appear...if some fields are not filled error class is attached properly.
What differentiates first from second submit(and if email is not changed) is the fact that ajax call for the email is not made.
So if ajax call is made(for the email) and returns true the above problem appears.
The code for the showerrors method found in the above Soverflow post does not help.
I must emphasize that if I remove the remote method for the email the problem is fixed
here is the code inside validate():
$('#bizuserform').validate({
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors == 1 ? '1 field is miissing!!!' : errors + ' fields are missing!!!';
$("#error_general span").empty().html(message);
$("#error_general").show();
} else {
$("#error_general").hide();
}
this.defaultShowErrors();
},
highlight: function(element, errorClass, validClass) {
if($(element).attr("id")=='staffclient_yes')
{
$('#staffclient_yes').parent().addClass(errorClass);
}
if($(element).attr("id")=='medical')
{
$('#medical').parent().addClass(errorClass);
}
$(element).addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
if($(element).attr("id")=='staffclient_yes')
{
$('#staffclient_yes').parent().removeClass(errorClass);
}
if($(element).attr("id")=='medical')
{
$('#medical').parent().removeClass(errorClass);
}
$(element).removeClass(errorClass).addClass(validClass);
},
onfocusout: false,
submitHandler: function(form,event) {
event.preventDefault();
//ajax request here...ommited for brevity
},
rules:{
name: {
required: function () {
return $('#coname').is(':blank');
},
normalizer: function( value ) { return $.trim( value );}
},
lastname: {
required: function () {
return $('#coname').is(':blank');
},
normalizer: function( value ) { return $.trim( value );}
},
coname: {
required: function () {
return $('#name,#lastname').is(':blank');
},
normalizer: function( value ) { return $.trim( value );}
},
buztype:{required:true
},
med_spec:{
required: function(element) {return $('#medical').is(':checked');}
},
password:{
required:true,
password:true,
normalizer: function( value ) { return $.trim( value );}
},
address:{ required: true,
normalizer: function( value ) { return $.trim( value );}
},
city:{ required: true,
normalizer: function( value ) { return $.trim( value );}
},
municipality:{ required: true,
normalizer: function( value ) { return $.trim( value );}
},
email:{required: true,
email: true,
remote: {
url: "email_validity.php",//if I remove the remote method here problem is fixed
type: "post"
},
normalizer: function( value ) { return $.trim( value );}
},
phone:{required:true,
normalizer: function( value ) { return $.trim( value );},
digits: true,
rangelength: [10, 14]
},
staff_to_client:{
required: "#staf_eng:visible"
}
},
messages:{
buztype:'',
staff_to_client:'',
med_spec:'',
coname:"",
name:'',
lastname:'',
password:{required:""
},
address:'',
city:'',
municipality:'',
email:{required:"",
email:'not valid email',
remote:'email allready exists.'
},
phone:{required:"",
rangelength:'phonenumber messasge.',
digits:'only digits here'
},
staff_to_client:{
required: ""
}
}
});
so I have this form (jsfiddle link) and as you can see, more selections appear once a radio option is selected. My problem is that if I click on submit and then select another radio button and then select the first radio option again, the validation has not cleared.
Is there a way do to this? I looked at the various options of the plugin but nothing stands out.
Thanks
here's my JS code:
$(document).ready(function(){
$("[id$=dob]").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd-mm-yy", yearRange: "-100:+0" });
$(document).on("click", "[id^=self_service_form_type_]", function(event) {
for (i=0; i < 2; i++) {
$("#type_"+i).hide();
}
$("#type_"+event.target.id.slice(-1)).show();
});
$('#selfserviceform').validate({
rules: {
"self_service_form[studentid]": {
required: {
depends: function() {
return $("#self_service_form_type_0").is(":checked");
}
}
}
, "self_service_form[studentdob]": {
required: {
depends: function() {
return $("#self_service_form_type_0").is(":checked");
}
}
}
, "self_service_form[hrnumber]": {
required: {
depends: function() {
return $("#self_service_form_type_2").is(":checked");
}
}
}
, "self_service_form[hrdob]": {
required: {
depends: function() {
return $("#self_service_form_type_2").is(":checked");
}
}
}
}
, focusCleanup: true
, messages: {
"self_service_form[studentid]": ""
, "self_service_form[studentdob]": ""
, "self_service_form[hrnumber]": ""
, "self_service_form[hrdob]": ""
}
, submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
I hope this link will be helpful to you.
$(document).ready(function(){
$("[id$=dob]").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd-mm-yy", yearRange: "-100:+0" });
$(document).on("click", "[id^=self_service_form_type_]", function(event) {
for (i=0; i < 2; i++) {
$("#type_"+i).hide();
}
$("#type_"+event.target.id.slice(-1)).show();
});
$('#selfserviceform').validate({
rules: {
"self_service_form[studentid]": {
required: {
depends: function() {
return $("#self_service_form_type_0").is(":checked");
}
}
}
, "self_service_form[studentdob]": {
required: {
depends: function() {
return $("#self_service_form_type_0").is(":checked");
}
}
}
, "self_service_form[hrnumber]": {
required: {
depends: function() {
return $("#self_service_form_type_2").is(":checked");
}
}
}
, "self_service_form[hrdob]": {
required: {
depends: function() {
return $("#self_service_form_type_2").is(":checked");
}
}
}
}
, focusCleanup: true
, messages: {
"self_service_form[studentid]": ""
, "self_service_form[studentdob]": ""
, "self_service_form[hrnumber]": ""
, "self_service_form[hrdob]": ""
}
, submitHandler: function (form) { // for demo
if($("#self_service_form_type_0").is(":Checked") == true)
{
$("#self_service_form_studentid").val('')
$("#self_service_form_studentdob").val('')
}
if($("#self_service_form_type_1").is(":Checked") == true)
{
$("#self_service_form_hrnumber").val('')
$("#self_service_form_hrdob").val('')
}
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
I'm using the kflorence jquery wizard: https://github.com/kflorence/jquery-wizard/ and I ran into an issue with validation when using branching.
I'd like to have the wizard show an error message instead of the defaulted "alert" when the selected option is blank. It currently works for regular steps, but when I get to a branched question, the validation does not work.
<script type="text/javascript">
jQuery(function($) {
$("#example-3" ).wizard({
transitions: {
q3: function( state, action ) {
var branch = state.step.find( "[name=q3]:selected" ).attr("class");
if (!branch ) {
????
}
return branch;
},
q5: function( state, action ) {
var branch = state.step.find( "[name=q5]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
},
q6: function( state, action ) {
var branch = state.step.find( "[name=q6]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
},
q7: function( state, action ) {
var branch = state.step.find( "[name=q7]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
},
q8: function( state, action ) {
var branch = state.step.find( "[name=q8]:selected" ).attr("class");
if ( !branch ) {
//alert( "Please select a value to continue." );
}
return branch;
}
},
beforeForward: function( event, state ) {
return !!$( this ).wizard( "form" ).valid();
},
afterSelect: function( event, state ) {
//$( "#progressbar2" ).progressbar( "value", state.percentComplete );
$( "#location2" ).text(Math.round(state.percentComplete) + "%");
if($('#unqualified').is(':visible')) {
$(".pad").hide();
} else {
$(".pad").show();
};
}
}).validate({
rules :{
q1: {
required: true
},
q2: {
required: true
},
q3: {
required: true
},
q4: {
required: true
},
q5: {
required: true
},
q6: {
required: true
},
q7: {
required: true
},
q8: {
required: true
}
}
});
});
</script>
I need the validation error to fire if the branch returns false.
I got it to work using:
if (!branch) {
$("form").valid();
}
I have a form with 5 input fields (4 text input, 1 checkbox) and I have written this code to handle missing information in the input fields. The code works fine but but it seems repetitive and inefficient. Is there a simpler way to write this code?
$("#main-form").on('submit', function(event) {
if (!$("#field1").val()) {
event.preventDefault();
$("#field1-error").html("Error!");
}
else
$("#field1-error").html("");
if (!$("#field2").val()) {
event.preventDefault();
$("#field2-error").html("Error");
}
else
$("#field2-error").html("");
if (!$("#field3").val()) {
event.preventDefault();
$("#field3-error").html("Error");
}
else
$("#field3").html("");
if (!$("#field4").val() && !$("#checkbox1").prop('checked')) {
event.preventDefault();
$("#field4-error").html("Error");
}
else
$("#field4-error").html("");
});
If the function does the same thing on multiple similar fields, it is best to just write one function. I think every Javascript engineer at some point or another has banged their head against a wall trying to come up with a slicker way run form validations.
For this situation I would write the function and call it whenever I needed it. Try this:
$("#main-form").on('submit', function(event) {
myValidations.contentsPresent('#field1', '#field1-error');//call the first field validaitions
myValidations.contentsPresent('#field2', '#field2-error');//second
//third
//etc
});
var myValidations =
{
contentsPresent: function(fieldId, errorId)
{
if (!$(fieldId).val()) {
event.preventDefault();
$(errorId).html("Error!");
}
else
$(errorId).html("");
}
},
contentsPresentCheckBox: function(fieledId, checkboxId, errorId)
{
if (!$(fieledId).val() && !$(checkboxId).prop('checked')) {
event.preventDefault();
$(errorId).html("Error");
}
else
$(errorId).html("");
}
}
}
//Try this.
$(document).ready(function(){
/** Form Validation */
$("#formId").validate({
rules: {
field1:{ required: true },
field2:{ required: true },
field3:{ required: true },
field4:{ required: true }
},
messages: {
field1:{ required: 'Field1 is required!' },
field2:{ required: 'Field2 is required!' },
field3:{ required: 'Field3 is required!' },
field4:{ required: 'Field4 is required!' }
}
// Submit function
});
// This is a simple jquery form validation but you need to include the jquery validation plugin.
http://jqueryvalidation.org/
I am trying to build a custom client side jquery validation and trying to ignore default values that i generate from HTML5 data attributes
$('input, textarea').each(function () {
if ($(this).data('val-default')) {
$(this).focus(function () {
if (this.value == $(this).data('val-default'))
this.value = '';
});
$(this).blur(function () {
if (this.value == '')
this.value = $(this).data('val-default');
});
this.value = $(this).data('val-default');
}
});
So with the above code i can add default values to input and textarea elements like this
data-val-default="Type your first name here"
Placeholder attribute is unfortunately not an option yet
The problem now is that i am trying to validate these elements with Jquery validation like this
$.validator.addMethod("ignoreDefaultValues",
function (value, element) {
if ($(element).data('val-default'))
return !($(element).data('val-default') == element.value);
return true;
},
"Required field"
);
$('form#contact-form').submit(function (e) {
e.preventDefault();
if (!$(this).valid({
rules:
{
title:
{
ignoreDefaultValues: true,
required: true
},
description:
{
ignoreDefaultValues: true,
required: true
},
name:
{
ignoreDefaultValues: true,
required: true
},
email:
{
ignoreDefaultValues: true,
required: true
}
}
})) {
alert("NOT VALID!");
}
else
{
alert("IS VALID!");
//todo: ajax post to server
}
});
Here is an example of an input element
<input type="text" class="firstname" name="firstname" data-val-default="Type your first name here" data-val="true" data-val-required="*" />
The jquery validation seems to ignore the rules. if i test for example by typing an empty space it will validate and alert "NOT VALID" but it just ignores my custom validation.
What am i doing wrong?
Have i missed anything?
You need to setup the validation before the submit function. So instead of doing $(this).valid(...) in your submit handler, instead do this beforehand:
$('form#contact-form').validate( { //your rules
,
submitHandler:function(){
alert('Is Valid!');
$(this).submit(); //or submit via AJAX, or whatever you planned...
},
invalidHandler:function(){
alert('Is not valid!');
}
});