PLEASE NOTE: These forums are no longer utilized and are provided as an archive for informational purposes only. All support issues will be handled via email using our support ticket system. For more detailed information on this change, please see this blog post.

ZIP code validation

  1. JossNL
    Member

    Hi there,

    I've been having some troubles with GravityForms... Or users, to be more precise. They seem to be mistaking the ZIP code field for street number. So I decided I need a validation on the ZIP code. Problem is... I use the advanced address field you guys supplied, and I can't get the validation to work on that. Our zip code (postcode) is made up out of 4 numbers, an optional space and 2 letters. The problem is probably in the field id. I tried it with
    $field_value = rgpost("input_{$field['id']}");
    and
    $field_value = rgpost("input_{$field['id']}.3");
    since the zipcode is in input_x.3

    Both fail. If I use it on a normal text line, the validation does work, but this is not an option.

    Full code:

    add_filter('gform_validation', 'validate_postcode');
    
    function validate_postcode($validation_result) {
    
        $form = $validation_result["form"];
        $current_page = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
        foreach($form['fields'] as &$field){
            if(strpos($field['cssClass'], 'postcode') === false)
                continue;
    
            $field_page = $field['pageNumber'];
            $is_hidden = RGFormsModel::is_field_hidden($form, $field, array());
    
            if($field_page != $current_page || $is_hidden)
                continue;
    
            $field_value = rgpost("input_{$field['id']}.3");
            $is_valid = is_postcode($field_value);
            if($is_valid)
                continue;
    
            $validation_result['is_valid'] = false;
            $field['failed_validation'] = true;
            $field['validation_message'] = 'De postcode is niet correct ingevuld.';
    
        }
    
        $validation_result['form'] = $form;
        return $validation_result;
    }
    
    function is_postcode($value) {
    	if (preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $value)) {
    		return true;
    	} else {
    		return false;
    	}
    }
    Posted 14 years ago on Friday August 5, 2011 | Permalink
  2. JossNL
    Member

    And of course you see what you're doing wrong only when you just hit submit.

    ZIP code is not in input_x.3 but in input_x_3
    I was looking at the name, not the ID.

    It's working now!

    Posted 14 years ago on Friday August 5, 2011 | Permalink
  3. That was easy :) Glad you figured it out.

    Posted 14 years ago on Friday August 5, 2011 | Permalink

This topic has been resolved and has been closed to new replies.