Home Forums ACF PRO Escaping & in text fields Reply To: Escaping & in text fields

  • I ran into this issue today. I sent a support ticket in with some more details. Just wanted to add on here.

    If you have a standard text input with a maxlength, it appears to be validating the string length after encoding HTML entities. That means an & character counts as 5 characters (& a m p ;).

    Unfortunately I couldn’t think of a “clean” solution that doesn’t override all other types of validations. The best I came up with is based on checking if the validation error contains the text “Value must not exceed” – which won’t work if the message changes or if your site is in another language.

    Below is my solution with those limitations in mind. It “fixes” regular text fields and also multi-line textareas. You can just remove the last line if you want to validate textareas normally.

     * Correct max length validation failures caused by html entities like & and < for text inputs.
     * @param string|true $valid
     * @param string $value
     * @param array $field
     * @param string $input_name
     * @return string|true
    function rs_fix_acf_length_validation( $valid, $value, $field, $input_name ) {
    	if ( is_string($valid) && strpos($valid, 'Value must not exceed') === 0 ) {
    		if ( !isset($field['maxlength']) ) return $valid; // maxlength should  be present here
    		// decode html entities (& -> &). particularly: &, <, >, ", '
    		$decoded_value = wp_specialchars_decode( $value );
    		// get new string length
    		$decoded_length = mb_strlen(wp_unslash( $decoded_value ));
    		// if the decoded string length fits within the max length, override the validtion.
    		if ( $decoded_length <= $field['maxlength'] ) $valid = true;
    	return $valid;
    add_filter( 'acf/validate_value/type=text', 'rs_fix_acf_length_validation', 20, 4 ); // Text and Textarea both support maxlength, as of ACF 5.8.11
    add_filter( 'acf/validate_value/type=textarea', 'rs_fix_acf_length_validation', 20, 4 );