0

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?

0

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();
    }; 
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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