Search code examples
ruby-on-railsmaxlength

One maxlength for multiple text fields


Hi say I have two text fields. I want to have just one maxlength for both of them. Wherein, for example 300 is the maxlength. And that is for both text fields. Is it possible to have 1 maxlength for multiple fields?


Solution

  • Edit:

    You will need to use jquery/javascript and client side validation. As a starting point

    Something like

    $('#text_field_1, #text_field_2').blur(function(){
      if($('#text_field_1').val() + $('#text_field_2').val() > 300){
        alert("Text Field max length has been reached");
      }
    });
    

    Building on that example you'll want to have a listener on form submission $().submit that will return false, show an error message, and stop submitting the form if the max length is greater that allowed.