Support

Account

Home Forums Add-ons Repeater Field How to FORCE exact number of characters on a Repeater Sub Field

Unread

How to FORCE exact number of characters on a Repeater Sub Field

  • Hello,

    I just spent several hours figuring out how to force a certain number of characters for a repeater sub field. We have some proprietary data that must contain exactly 6 digits. I searched the forums and documentation and couldn’t find anything about how to do this there.

    After trying many convoluted approaches that did not work, the solution was actually quite simple. I was trying to determine the auto-generated array index for the subfield so that I could then retrieve the value of it but that was not the right approach. Instead the $value attribute of the function already contains the value so it didn’t need to be retrieved at all.

    So, to hopefully save others time in the future, I am posting the simple solution that I came up with here. It uses the “validate_value” filter.

    
    // FORCE each subfield of a repeater field to be EXACTLY 6 characters
    add_filter('acf/validate_value/name=subfield_name', 'vh_validate_sub_field', 10, 4);
    
    function vh_validate_sub_field( $valid, $value, $field, $input ) {
     
    	// bail early if value is already invalid
    	if( !$valid ) {
    		return $valid;
    	}
        
        if ( strlen($value) != 6 ) {
    		$valid = 'The sub field MUST contain EXACTLY 6 characters. Your entry contains ' . strlen($value) . ' characters.';
    	}
        
    	// return
    	return $valid;
     
    }
    

    NOTES:

    1.) Make sure to change “subfield_name” to the name of your subfield.

    2.) You can change the “6” in:

    
    ( strlen($value) != 6 )
    

    to whatever you want if you need an exact number of digits other than 6.

    Best,
    Jack

Viewing 1 post (of 1 total)

The topic ‘How to FORCE exact number of characters on a Repeater Sub Field’ is closed to new replies.