I need to add custom error messages for Ninja Forms used in wordpress

189 Views Asked by At

I am using Ninja Forms in my WordPress project. I need to add custom messages for phone number and name validation.Now we are able to submit form with number in text field and text in phone number field. As of now only email and empty field validation is present.

I tried using jQuery, to add both the errors, but even with the errors am able to submit the form.

jQuery(document).ready(function () {
  jQuery(document).on("nfFormReady", function () {
    var form = jQuery("form"); 
    var submitButton = form.find('input[type="button"]');

    jQuery('input[type="text"]').focusout(function () {
      // jQuery('input[type="text"]').on("input", function () {
      var inputValue = $(this).val();
      var lettersRegex = /^[a-zA-Z]+$/;
      var errorMsg = "Please enter only letters";

      if (inputValue === "") {
        return $(this)
          .parents(".nf-field")
          .next(".nf-after-field")
          .find(".nf-error-wrap")
          .html("")
          .show();
      }

      if (!lettersRegex.test(inputValue)) {
        $(this)
          .parents(".nf-field")
          .next(".nf-after-field")
          .find(".nf-error-wrap")
          .html(
            '<div class="nf-error-msg nf-error-required-error">' +
              errorMsg +
              "</div>"
          )
          .show();
      } else {
        $(this)
          .parents(".nf-field")
          .next(".nf-after-field")
          .find(".nf-error-wrap")
          .html("")
          .show();
      }
    });

    jQuery('input[type="tel"]').on("input", function () {
      var inputValue = $(this).val();
      var numRegex = /^\d+$/;
      var errorMsg = "Please enter only numbers";

      if (inputValue === "") {
        return $(this)
          .parents(".nf-field")
          .next(".nf-after-field")
          .find(".nf-error-wrap")
          .html("")
          .show();
      }

      if (!numRegex.test(inputValue)) {
        $(this)
          .parents(".nf-field")
          .next(".nf-after-field")
          .find(".nf-error-wrap")
          .html(
            '<div class="nf-error-msg nf-error-required-error">' +
              errorMsg +
              "</div>"
          )
          .show();
      } else {
        $(this)
          .parents(".nf-field")
          .next(".nf-after-field")
          .find(".nf-error-wrap")
          .html("")
          .show();
      }
    });

    var errorMessages = form.find(".nf-error-msg");
    if (errorMessages.length > 0) {
      submitButton.prop("disabled", true);
    } else {
      submitButton.prop("disabled", false);
    }
  });
});
0

There are 0 best solutions below