Skip Navigation

[Résolu] Struggling with JS client side form validation

Ce fil est résolu. Voici une description du problème et la solution proposée.

Problem: I am trying to add some custom JavaScript form validation to a CRED form, but it doesn't seem to be working as expected.

Solution: Bind to the window.load event, not the document ready event, to initialize form event handlers. Use the jQuery namespace instead of "$" to access the jQuery object. Here is a template:

jQuery(window).bind('load', function() {
  
  // Your custom validation code goes here using jQuery instead of $
});
This support ticket is created Il y a 5 années et 11 mois. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 14 réponses, has 3 voix.

Last updated by johnR-22 Il y a 5 années et 10 mois.

Assisted by: Christian Cox.

Auteur
Publications
#893152

Im trying to ensure that a user completes a certain form field when editing at the front end, and Im using the following snippet of code to do so, however Im not having any luck.

What have I missed?

jQuery(document).ready(function($){
$("#cred_form_290_1").on("submit", function(){
var my_field = $("input[wpcf-edit-summary]").val();

if(my_field == "") {
alert("Please enter a value.");
$("input[wpcf-edit-summary]").focus();
return false;
}
});
});

PS - I dont want to set the field as required because this then becomes an annoyance when working in the admin backend.

Thanks guys.

#894352

Shane
Supporter

Languages: Anglais (English )

Timezone: America/Jamaica (GMT-05:00)

Hi John,

Thank you for contacting our support forum.

Would you mind providing me with a link to the page where the form is on the frontend so that I can take a look at this ?

Also the correct way to do the custom validations can be seen below.
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

Please let me know if this helps.
Thanks,
Shane

#894817

Hi Shane,
Thanks for responding.

Im working on localhost (testing) so I cant provide you with a URL, but I've stripped out the code for you below. (Ive trimmed this back a little so I didnt dump a whole lot of code here) Hopefully I havent missed anything.

<form  id="cred_form_290_1" class="cred-form cred-keep-original" action="/romaines/vehicle/1971-ford-xy-falcon-gtho-phase-3/?layout_id=289&_tt=1526515451" method="post">



	<div class="form-group">
		<label>Edit Summary (Briefly describe your changes)</label>
		<div class="js-wpt-field-items js-wpt-repetitive wpt-repetitive" data-initial-conditional="" data-item_name="textarea-wpcf-edit-summary">
<textarea id="cred_form_290_1-textarea-1-1526515452" name="wpcf-edit-summary" class="form-control wpt-form-textarea form-textarea textarea" output="bootstrap" preset_value="" urlparam="" value_escape="" make_readonly="" placeholder="" rows="5" cols="1" data-wpt-type="textarea" data-wpt-id="cred_form_290_1_cred_form_290_1-textarea-1-1526515452" data-wpt-name="wpcf-edit-summary"></textarea>

</div>
	</div>

<input type="submit" id="cred_form_290_1-submit-1-1526515452" name="form_submit_1" value="Submit for Review" class="btn btn-primary btn-lg wpt-form-submit form-submit submit" />

<input type="hidden" id="cred_form_290_1-hidden-2-1526515452" name="_cred_cred_wpnonce_cred_form_290" value="97004a92f6" class="wpt-form-hidden form-hidden" data-wpt-id="cred_form_290_1_cred_form_290_1-hidden-2-1526515452" data-wpt-name="_cred_cred_wpnonce_cred_form_290" /><input type="hidden" id="cred_form_290_1-hidden-3-1526515452" name="_cred_cred_prefix_post_id" value="279" class="wpt-form-hidden form-hidden" data-wpt-id="cred_form_290_1_cred_form_290_1-hidden-3-1526515452" data-wpt-name="_cred_cred_prefix_post_id" /><input type="hidden" id="cred_form_290_1-hidden-4-1526515452" name="_cred_cred_prefix_cred_container_id" value="279" class="wpt-form-hidden form-hidden" data-wpt-id="cred_form_290_1_cred_form_290_1-hidden-4-1526515452" data-wpt-name="_cred_cred_prefix_cred_container_id" /><input type="hidden" id="cred_form_290_1-hidden-5-1526515452" name="_cred_cred_prefix_form_id" value="290" class="wpt-form-hidden form-hidden" data-wpt-id="cred_form_290_1_cred_form_290_1-hidden-5-1526515452" data-wpt-name="_cred_cred_prefix_form_id" /><input type="hidden" id="cred_form_290_1-hidden-6-1526515452" name="_cred_cred_prefix_form_count" value="1" class="wpt-form-hidden form-hidden" data-wpt-id="cred_form_290_1_cred_form_290_1-hidden-6-1526515452" data-wpt-name="_cred_cred_prefix_form_count" /></form></div></div></div>  

And of course the JS below

<script type='text/javascript' class='custom-js'>


jQuery(document).ready(function($){
    $("#cred_form_290_1").on("submit", function(){
        var my_field = $("input[wpcf-edit-summary]").val();
 
        if(my_field == "") {
            alert("Please provide required input as required.");
            $("input[wpcf-edit-summary]").focus();
            return false;
        }
    });
});
</script>

This was all taken from the HTML output.

Cheers

#897848

Shane
Supporter

Languages: Anglais (English )

Timezone: America/Jamaica (GMT-05:00)

Hi John,

From what I can see your code looks correct and should work.

Thanks,
Shane

#899854

Yeah Im not sure whats going on, it definitely doesnt work.

Im using Google Chrome.

#901118

Shane
Supporter

Languages: Anglais (English )

Timezone: America/Jamaica (GMT-05:00)

Hi John,

Lets use the php validation hook for this instead as this is the method our developers created for the validations.

However first I need to know what kind of field is it.

Is it a WYSIWYG field or just a simple text field.

Please let me know.
Thanks,
Shane

#902572

Hi Shane,
Ive finally had time to revisit this.

Trying again, still no luck.

[credform class='cred-form cred-keep-original']

[cred_field field='form_messages' value='' class='alert alert-warning']

<div class="form-group">
<label>Vehicle Description</label>
[cred_field field='post_content' post='vehicle' value='' urlparam='' output='bootstrap']
</div>

Vehicle Specifications
<div class="row">
<div class="col-sm-6"><label>Make</label>
[cred_field field='make' post='vehicle' value='' urlparam='' class='form-control' output='bootstrap']</div>
<div class="col-sm-6"><label>Model</label>
[cred_field field='model' post='vehicle' value='' urlparam='' class='form-control' output='bootstrap']</div>
</div>

<div class="hidden">
[cred_field field='revision-author' post='vehicle' value='[wpv-current-user]' urlparam='']
[cred_field field='revision-email' post='vehicle' value='[wpv-current-user info="email"]' urlparam='']
</div>

<div class="form-group">
<label>Edit Summary (Briefly describe your changes)</label>
[cred_field field='revision-summary' post='vehicle' value='' urlparam='' class='form-control' output='bootstrap']
</div>

[cred_field field='form_submit' value='Submit for Review' urlparam='' class='btn btn-primary btn-lg' output='bootstrap']

[/credform]

-------------------------------------------------------

jQuery(function( $ ) {

// Validation
$( '#cred_form_290_1' ).submit( function() {

// content
if ( $( "input[wpcf-revision-summary]" ).val() == '') {
$( "input[wpcf-revision-summary]" ).focus();
alert( "Please complete the revision summary field" );
return false;
}
} );

#902578

Hi, Shane is unavailable today so I'd like to try to help. First, let's confirm the event listener is being added appropriately. Add an alert right inside the submit listener:

jQuery(function( $ ) {

// Validation
$( '#cred_form_290_1' ).submit( function() {
alert('submit');
// content
if ( $( "input[wpcf-revision-summary]" ).val() == '') {
$( "input[wpcf-revision-summary]" ).focus();
alert( "Please complete the revision summary field" );
return false;
}
} );

Assuming the ID #cred_form_290_1 is correct, you should see the alert when you submit the form. If not, then we can assume that the event listener is being bound before the CRED form is ready to accept event bindings. To fix that, you can try to listen to another event:

jQuery(window).bind('load', function(){
  // Validation
jQuery( '#cred_form_290_1' ).submit( function() {
alert('submit');
// content
if (jQuery( "input[wpcf-revision-summary]" ).val() == '') {
jQuery( "input[wpcf-revision-summary]" ).focus();
alert( "Please complete the revision summary field" );
return false;
}
});

Notice that I have replaced the $ namespace with jQuery here. Let me know what you find out and we can go from there.

#902665

Thanks Christian. No luck again unfortunately.

Here's the HTML output, maybe this might help.

<script type='text/javascript' class='custom-js'>


jQuery(window).bind('load', function(){
  // Validation
jQuery( '#cred_form_290_1' ).submit( function() {
alert('submit');
// content
if (jQuery( "input[wpcf-revision-summary]" ).val() == '') {
jQuery( "input[wpcf-revision-summary]" ).focus();
alert( "Please complete the revision summary field" );
return false;
}
});
</script>
<form  id="cred_form_290_1" class="cred-form cred-keep-original" action="/romaines/vehicle/1972-xa-ford-falcon-coupe-superbird/?layout_id=289&_tt=1527124762" method="post">

<div id="wpt-form-message-290" data-message-single="The post was not saved because of the following problem:"
			              data-message-plural="The post was not saved because of the following %NN problems:"
			              style="display:none;" class="wpt-top-form-error wpt-form-error alert alert-danger"></div>



	<div class="form-group">
		<label>Edit Summary (Briefly describe your changes)</label>
		<div class="js-wpt-field-items js-wpt-repetitive wpt-repetitive" data-initial-conditional="" data-item_name="textarea-wpcf-revision-summary">
<textarea id="cred_form_290_1-textarea-1-1527124762" name="wpcf-revision-summary" class="form-control wpt-form-textarea form-textarea textarea" output="bootstrap" preset_value="" urlparam="" value_escape="" make_readonly="" placeholder="" rows="5" cols="1" data-wpt-type="textarea" data-wpt-id="cred_form_290_1_cred_form_290_1-textarea-1-1527124762" data-wpt-name="wpcf-revision-summary"></textarea>

</div>
	</div>

<input type="submit" id="cred_form_290_1-submit-1-1527124762" name="form_submit_1" value="Submit for Review" class="btn btn-primary btn-lg wpt-form-submit form-submit submit" />

</form>
#902926

Is this form available on your site for me to test? If I need to log in, please provide login credentials in the private reply fields here.

#902952

Im working on localhost Christian.

Sorry mate.

#903019

I can test a clone of your site if it's not available online. You can install the Duplicator plugin (its free) and create a clone, then post that archive on Dropbox or Drive somewhere and share a download link. If Duplicator is not a good option, you can try the WP All-in-One Migration plugin. The 3rd option is to provide a zip archive containing your plugins and theme folders and a SQL dump from your database. I can work from any of those 3 options. I will activate a private reply field here where you can share a download link confidentially. The field says "Duplicator package" but you can add any download link.

#903104

Three problems:
1. There is a syntax error in your JavaScript code, it's missing a closing });
2. You must wait for the window 'load' event to initialize your submit handler, otherwise CRED initialization will delete it.
3. The selector input[wpcf-revision-summary] is not correct.

Changes below:

jQuery(window).bind('load', function() {
 
  // Validation
  jQuery( '#cred_form_290_1' ).submit( function() {
    // content
    if ( jQuery( "textarea[name='wpcf-revision-summary']" ).val() == '') {
      jQuery( "textarea[name='wpcf-revision-summary']" ).focus();
      alert( "Please complete the revision summary field" );
      return false;
    }
  } );
} );
#903358

Excellent Christian thank you very much!

One quick question, how would I go about adding a checkbox in there as well?

Terms and service agreement before completing the form

#904289

All good mate I got it working.

Thank you so much for helping me, I really appreciate it.

<div class="form-group">
		<label>Edit Summary (Briefly describe your changes)</label>
		[cred_field field='revision-summary' post='vehicle' value='' urlparam='' class='form-control' output='bootstrap']
	</div>

<div class="form-group">	
[cred_generic_field field='agree' type='checkbox' class='' urlparam='']
{
"required":1,
"validate_format":0,
"checked":0,
"default":"1",
"label":"By submitting this change you agree to our terms of use"
}
[/cred_generic_field]
  
  
[cred_show_group if="($(agree) eq  '1' )"  mode='fade-slide']
PLEASE NOTE - All changes are reviewed by a moderator before being posted live, which is usually done within 24 hours if not sooner. Thank you for contributing.
[/cred_show_group]

</div>
This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.