1

I want to implement client side validation using jQuery on my custom form.

I have enabled clientside validation contributed module

I have successfully attached custom js file using following code:

 $form['#attached']['library'][] = 'custom_form/cl-validation';

And in the JS file I have written below code:

(function ($, Drupal) {
  Drupal.behaviors.custom_form = {
    attach: function (context, settings) {

        var selectedCountry = ''

        $("#country").change(function(){
          selectedCountry = $(this).children("option:selected").val();

        });


        $('#user-number-value').keyup(function(){   
              $(this).val($(this).val().replace(/(\d{2})|([a-z]{2})\-?/,'$1-'))
        });

         $("input#user-number-value").focus(function() { 
            if(selectedCountry == undefined || selectedCountry == '') {
                $('#user-number-value').va('')
               // I want mark country dropdown as red and show a error
            }
        });


    }
  };
})(jQuery, Drupal);

I am not getting how to do this using jquery and stop form submission.

Any help?

1 Answer 1

1

If the form field is empty you need to stop propagation of the parent form. This should be what you need.

 countryValidation = function() {
    // Lets use a function so we can check the field
    $country = $('#country');
    if ($country.val() === '') {
      return false;
    } else {
      return true;
    }
  }

  $('#user-number-value').on('focus', function(){
    if(countryValidation() === false){
      // If the field check comes back false on focus lets add a class
      $('#country').addClass('invalid');
    };   
  });

  $('#country').on('change', function(){
    // This will remove the class when the user fixes the error
    if(countryValidation() === true) {
      $('#country').removeClass('invalid'); 
    } else {
      $('#country').addClass('invalid');
    }   
  });

  $('form').on('submit', function(e) {
    if(countryValidation() === false){
      // when the field comes back invalid lets add the class
      $('#country').addClass('invalid');
      // this will prevent the form from submitting
      e.preventDefault();
    }; 
  });
3
  • How would you display a message to that? please
    – Alex Seif
    Apr 10, 2022 at 12:12
  • @AlexSeif You can use the invalid/valid class to toggle a message if you wanted.
    – Brad O
    Apr 11, 2022 at 12:51
  • ty, it was kind of a challenge, coz I also had the pattern attribute, so it overrides my validation result, depending on which is triggered first. I ended up with server side validation. But I wanted to display a unique message for a unique scenario
    – Alex Seif
    Apr 12, 2022 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.