Jump to content

Limit Character Count on Forms

Go to solution Solved by creedon,

Recommended Posts

On 7/14/2021 at 7:44 AM, shrineofourladyoftheisland said:

Sorry about that.

No worries.

Please see the following.

Let us know how it goes.

Edited by creedon

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
22 hours ago, creedon said:

No worries.

Add the following to Settings > Advanced > Code Injection > HEADER.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="https://d1j8mu9lowy9zf.cloudfront.net/twcsl/0.1d8/twcsl.js"></script>

Add the following to Store Settings > Advanced > Page Header Code Injection for the store page.

<script>

  $( ( ) => {
  
    /*
    
      set max length for store product detail named form and labeled text fields
      
      Version       : 0.1d0
      
      SS Version    : 7.1
      
      Dependancies  : jQuery
                      
                      twcsl
      
      By            : Thomas Creedon < http://www.tomsWeb.consulting/ >
      
      */
      
    const formName = 'Inscription Form';
    
    const formFieldLabels = [
    
      /*
      
        the format of each line is a form text field label. in this context text
        field means either an input tag with type of text or textarea tag
        
        following is an example line. copy the example line below and paste
        after the example line. remove '// ' at beginning of pasted line. repeat
        for as many form field labels as you want to set the max character
        length
        
        */
        
      // '[enter form text field label here between single quotes]',
      
      'Line 1:',
      'Line 2:',
      'Line 3:',
      'Line 4: (ONLY for big bricks)',
      'Line 5: (ONLY for big bricks)',
      
      ];
      
    const skuMaxLengthMap = {
    
      /*
      
        the format of each line is a product sku and a max character length for
        for named text form fields
        
        following is an example line. copy the example line below and paste
        after the example line. remove '// ' at beginning of pasted line. repeat
        for as many product skus you want to set the max character length for
        named text form fields
        
        */
        
      // '[enter product sku here between single quotes]' : [enter text field max character length here between single quotes],
      
      'L40a' : 15,
      'L40b' : 20,
      
      };
      
    // do not change anything below, there be the borg here
    
    if ( ! twcsl.storePage.isDetail ) return; // bail if not detail
    
    const sku = Static.SQUARESPACE_CONTEXT.product.variants [ 0 ].sku;
    
    // bail if sku not defined
    
    if ( ! skuMaxLengthMap.hasOwnProperty ( sku ) ) return;
    
    // bail if no mutation observer available
    
    if ( ! ( 'MutationObserver' in window ) ) return;
    
    // begin get form field label
    
      var getFormFieldLabel = $field => {
      
        const title = $( '.title', $field )
        
          .clone ( )
          
          .children ( )
          
          .remove ( )
          
          .end ( )
          
          .text ( )
          
          .trim ( );
          
        return title;
        
        }
        
      // end get form field label
      
    // begin get form field text labeled
    
      var getFormFieldTextLabeled = ( label, $form ) => {
      
        let $it = undefined;
        
        $( '.text, .textarea', $form ).each ( function ( ) {
        
          const $this = $( this );
          
          const title = getFormFieldLabel ( $this );
          
          if ( title != label ) return true; // bail if 
          
          $it = $( 'input, textarea', $this );
          
          return false;
          
          } );
          
        return $it;
        
        }
        
      // end get form field text labeled
      
    const observer = new MutationObserver ( function ( mutations ) {
    
      $.each ( mutations, function ( ) {
      
        if ( ! this.addedNodes.length ) return; // bail if no nodes added
        
        const $e = $( this.addedNodes [ 0 ] );
        
        // bail if not dialog
        
        if ( ! $e.hasClass ( 'sqs-modal-lightbox' ) ) return;
        
        // bail if not form name
        
        if ( $( '.form-title', $e ).text ( ) != formName ) return;
        
        const $form = $( 'form', $e );
        
        let selectedVariant = $( '.product-variants' )
        
          .attr ( 'data-selected-variant' );
          
        selectedVariant = JSON.parse ( selectedVariant );
        
        const sku = selectedVariant.sku;
        
        if ( ! ( sku in skuMaxLengthMap ) ) return; // bail sku not defined
        
        $.each ( formFieldLabels, function ( i, fieldLabel ) {
        
          const $text = getFormFieldTextLabeled ( fieldLabel, $form );
          
          if ( $text === undefined ) return true; // continue if no element
          
          const maxLength = skuMaxLengthMap [ sku ];
          
          $text.attr ( 'maxLength', maxLength );
          
          let value = $text
          
            .val ( )
            
            .slice ( 0, maxLength );
            
          $text.val ( value );
          
          } ); // end each formFieldLabels
          
        } ); // end each mutations
        
      } ); // end MutationObserver
      
    // start listening for changes in body
    
    $( document.body ).each ( function ( ) {
    
      observer.observe ( this, { childList : true } );
      
      } );
      
    } );
    
  </script>

You'll need to add skus and max lengths to skuMaxLengthMap.

Just a note. The cart page allows the user to edit the form from that page and so you'll probably want a similar piece of code there to control the max length there.

Also the checkout page allows editing of the form as well. SS does not allow custom code on the checkout page. It is a security feature. So you will need to manually check the character length of each order and take corrective action for those orders that exceed the max characters.

Let us know how it goes.

Thank you so much!! This worked great!

Link to comment
  • 2 weeks later...

Dear @Creedon,

Can I kindly ask you for your help?

I have created a gift form where I allow people to leave a gift message but it has to be maximum 80 characters can you please help me with the code?

Website www.glassitude.com

Gift form is set up at the check out.

Website password Seaside.

 

Thank you for your help and time.

Kind regards,
Georgia

Link to comment

@Georgiawhoknows

The checkout page can not be modified it is a SS security feature. If you can add the form to the product detail then that from can be modified.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
4 hours ago, Georgiawhoknows said:

Would it be possible for you to create a code for 80 characters gift message?

Yes indeedy!

Please see my November 21, 2020 post earlier in this thread. The code linked to there should do the trick.

You'll want to set the following for your need.

    const formName = 'Gift message';
    
    const maxLength = 80;
    
    const formFieldLabel = 'Gift message';
    

Let us know how it goes.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
On 7/29/2021 at 1:54 AM, creedon said:

Yes indeedy!

Please see my November 21, 2020 post earlier in this thread. The code linked to there should do the trick.

You'll want to set the following for your need.

    const formName = 'Gift message';
    
    const maxLength = 80;
    
    const formFieldLabel = 'Gift message';
    

Let us know how it goes.

Dear Thomas!

I have tried using your code but it doesn't seem to be working. Do you know what could be an issue?

Thank you for your help.

Kind regards,

Georgia

<script>

  $( ( ) => {

    /*
    
      set store product detail named form labeled text field character max
      length
      
      Version         : 0.2d0
      
      SS Versions     : 7.0, 7.1
      
      v7.0 Templates  : Brine ( Aria, Blend, Burke, Cacao, Clay, Fairfield,
                        Feed, Foster, Greenwich, Hatch, Heights, Hunter, Hyde,
                        Impact, Jaunt, Juke, Keene, Kin, Lincoln, Maple, Margot,
                        Marta, Mentor, Mercer, Miller, Mojave, Moksha, Motto,
                        Nueva, Pedro, Pursuit, Rally, Rover, Royce, Sofia,
                        Sonora, Stella, Thorne, Vow, Wav, West )
                        
                        your template is not listed? then it is not currently
                        supported
      
      Dependancies    : jQuery
                        
                        twcsl
      
      Notes           : this code is for forms added as part of the product
                        editor :
                        
                          Classic Editor > Form or
                          
                          New Editor > Customize > Custom Forms
                          
                        it is not for forms added through :
                        
                          Classic Editor > Additional Info or
                          
                          New Editor > Customize > Additional Info
                          
                        a text form field is either a text or text area field
      
      By              : Thomas Creedon < http://www.tomsWeb.consulting/ >
      
      */

    /* for formName copy the value from the form editor Form Name field. you
       only need exactly what can be selected from the field */

    const formName = 'Gift message';

    const maxLength = 80;

    /* for formFieldLabel copy the value from the form Text Area field editor
       LABEL field. you only need exactly what can be selected from the field */

    const formFieldLabel = 'Gift message';

    // do not change anything below, there be the borg here

    if ( ! twcsl.storePage.isDetail ) return; // bail if not detail

    // bail if no mutation observer available

    if ( ! ( 'MutationObserver' in window ) ) return;

    // begin get form field text labeled

      var getFormFieldTextLabeled = ( label, $form ) => {

        let $it = undefined;

        $( '.text, .textarea', $form ).each ( function ( ) {

          const $this = $( this );

          const title = twcsl.getFormFieldLabel ( $this );

          if ( title != label ) return true; // continue if not our field

          $it = $( 'input, textarea', $this );

          return false;

          } );

        return $it;

        }

      // end get form field text labeled

    const observer = new MutationObserver ( function ( mutations ) {

      $.each ( mutations, function ( ) {

        if ( ! this.addedNodes.length ) return;

        let $element = $( this.addedNodes [ 0 ] );

        if ( ! $element.hasClass ( 'sqs-modal-lightbox' ) ) return;

        if ( $( '.form-title', $element ).text ( ) != formName ) return;

        const $form = $( 'form', $element );

        const $text = getFormFieldTextLabeled ( formFieldLabel, $form );

        if ( $text === undefined ) return true; // continue if no element

        $text.attr ( 'maxLength', maxLength );

        } );

      } );

    // start listening for changes in body

    observer.observe ( document.body, { childList : true } );

    } );

  </script>

Link to comment

@Georgiawhoknows

My bad the Read Me Quick Install instructions were missing a critical line at the beginning. I have updated the text. Please re-read them. You only need to do the first step as it appears as you've done the rest.

Let us know how it goes.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
  • 1 month later...
On 9/13/2021 at 9:54 AM, archeoanalytics said:

I have a similar request, except I want to have a set character count on a regular form. We are using it to "verify" EBT card numbers (which are 19 characters long). Is it possible to set this up?

The form is at the bottom of this page: https://www.cultureconnected.org/discounted-tix-ebt

Have you solved it yet?

Email me if you have need any help (free, of course.). Answer within 24 hours. 
Or send to forum message

Contact Customer Care - Learn CSS - Buy me a coffee (thank you!)

Link to comment
7 hours ago, tuanphan said:

@Liza I remember you posted a similar question. Try the above code.

@tuanphan, I didn't because the window I needed it has past and I was worried about adding that much code when a tiny snippet worked previously. I'm going to hang tight until I need it again, which shouldn't be for another year. Thanks for checking in on me. 

Link to comment

My code can tend to look longer but I don't knowingly throw in excessive code. Many of my solutions are more general purpose. If my code can be made to help several members then that is how I write it. General purpose code, if done correctly, should be commented so as to help people who, for the most part, don't know coding at all have a chance to understand what the code is doing and how to configure it.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

@MarianellaMoreno

It's hard to help without more detail. Which form? Which fields? What limits?

Please post the URL for a page on your site where we can see your issue.

If your site is not public please set up a site-wide password, if you've not already done so.

Post the password here.

Adding a site-wide password is not a security breach. Please read the documentation at the link provided to understand how it works.

Please read the documentation at the link provided on how to share a link to your site to understand how it works. A link to the backend of the your site won’t work for us, i.e. a url that contains /config/.

We can then take a look at your issue.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

@archeoanalytics

A maximum amount of characters is not to hard to accomplish. There are several threads on how to do that. Those pieces of code are simply adding a HTML built-in attribute (maxlength) to the form field that prevents more than the max number of characters being entered.

Unfortunately making other kinds of similar changes is not easy. Adding the minlength attribute would be nice but just adding it doesn't work. Even if you remove the novalidate attribute from the form.

Working around these form issues is complex, if doable at all.

Another big issue is that these workarounds are happening client side. That means that someone could get around your validations fairly easily. In other words it is not a robust method of checking input.

SS's form facilities are really very basic. If you need more robust form services people tend to look outside SS for that. Then embed those forms in their pages with a code block. Jotform seems to be a popular service.

Edited by creedon

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

I have updated my cited code in my Nov, 21, 2020 post. Fixed some bugs for descriptions where you want to use ftfml and have a description for the user as well.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

I have updated my cited code in my Nov, 21, 2020 post.

The main changes are deepening where the effect is active. I moved recognition of the ftfml directives from description to placeholder.

Edited by creedon

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment
  • 1 year later...
58 minutes ago, ThePromoTeam said:

What was the code that you used. I didn't see it in the conversation feed.

The code is referenced in my post prior to yours.

Find my contributions useful? Please like, upvote, mark my answer as the best ( solution ), and see my profile. Thanks for your support! I am a Squarespace ( and other technological things ) consultant open for new projects.

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.