Home > front end >  Prevent form from submitting does not work in wordpress with jquery
Prevent form from submitting does not work in wordpress with jquery

Time:09-13

I have a wordpress site (v.6.0.2) and I also have a contact form built with the WPForms plugin. What I am trying to do is to prevent the form from submitting when the name field does not contain two words (Name and Surname) in order to restrict spam messages.

In the functions.php I registered my script in the following way:

add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

function my_theme_scripts() {
    wp_register_script('my_script', get_template_directory_uri() . '/js/my_script.js', array('jquery'),'1.1', true);
    wp_enqueue_script( 'my_script' );
}

my_script.js in the js folder of my theme is:

$.noConflict();
jQuery(document).ready(function() {

$("#wpforms-form-2185").submit(function( event ) {
    $("input#wpforms-2185-field_0").each(function() {
        var words = $.trim($(this).val()).split(" ");
        //alert(words.length);
        if(words.length != 2) {
            event.preventDefault();
        }
    });
  });
});

What am I doing wrong and my form keeps submitting in every way I put names on?

Edit 1 My form gets submitted even with a single name word. These are the info messages from the Chrome console:

Screenshot 1 enter image description here

Screenshot 2 enter image description here

and the code from the formSubmit from the wpforms.min.js?ver=1.7.6:formatted:

 formSubmit: function(e) {
        e instanceof jQuery || (e = p(e)),
        l.saveTinyMCE();
        let t = WPFormsUtils.triggerEvent(e, "wpformsBeforeFormSubmit", [e]);
        t.isDefaultPrevented() ? l.restoreSubmitButton(e, e.closest(".wpforms-container")) : e.hasClass("wpforms-ajax-form") && "undefined" != typeof FormData ? l.formSubmitAjax(e) : l.formSubmitNormal(e)
    },

I am not a js expert but I think the above code is responsible for form submitting in any case.

CodePudding user response:

You are not preventing spam this way, because your form can still be submitted regardless of javascript or html. Also, might consider using required attribute on the form fields.

Your code works. Make sure you are having the fields with the correct id's . and if those are the correct id's then they are not recommended this way because id`s should be unique.

jQuery(document).ready(function() {

  $("#wpforms-form-2185").submit(function(event) {
    $("input#wpforms-2185-field_0").each(function() {
      var words = $.trim($(this).val()).split(" ");
      //alert(words.length);
      if (words.length != 2) {
        event.preventDefault();
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<form id="wpforms-form-2185">
  <input id="wpforms-2185-field_0">
  <input type="submit">
</form>

CodePudding user response:

I'm doing a lot of this kind of thing in my own application that uses WPForms extensively. I often find myself needing more nuanced form validation. My first thought on reading your question was to use Input Mask, but I'm not totally sure that would prevent the form submit, it might though, here's some documentation, and seems like you could use an input mask something like:

Aa{1,25} Aa{1,25}

If that works, that's probably the easiest solution, however, that's gonna require you to place some intentional limitations on the length of your names and maybe you don't want to do that, and as I said, I don't know exactly how the input masks work with the form validation.

So, an alternative would be to tap into the library that WPForms uses for form validation, jquery-validation. After your form loads, you can add custom validation rules to any of the fields. Here's some example code:

First, when the page loads, you extend the validation plugin's rules like this:

if($.validator) {
    $.validator.addMethod("two_words", function(value, element, params) {
        return this.optional( element ) || ($.trim(value).split(" ")).length==2;
    }, 'Field must contain two words.');
}

Here, I'm just adding a rule with the key 'two_words' that just checks whether the field is optional or meets the criteria you specified.

Then, when the form loads, you can add your rule to a specific field like this:

self.wpFormsField(formId,10).rules("add", {
    required: true,
    two_words: true,                                
    messages: {
        required: "Gotta know who you is sucka!",
        two_words: "Field must contain two words brosephus!"
    }
});

First I'm just selecting the WPForms field I want to add my rule to (using my own convenience function, don't worry about that, you can just select the field using it's id, e.g., $("#wpforms-formId-field_fieldId").rules...). Then, I'm passing an object that specifies my rule 'two_words' as true. I'm also marking the field as required here, but you can do that from the form creation screen as well. And finally, I'm specifying some custom messages for each of the rules I've added. If you don't specify these here, it will just use the default message for the given validation rule.

And that's it. I tested it out and it seems to do the trick:

Fails Validation - Field is Required

Fails Validation - Only One Word Given

Passes Validation - Two Words Given

Note that there are a number of different ways you can add validation rules to fields, including doing so without extending the plugin's rule set, I'm just doing it this way because I'm loading a lot of my forms on demand. Check the plugin rules documentation for more.

Good luck!

  • Related