Reputation: 334
I have added extra registration fields to the WooCommerce registration form. Among these fields are fields for state and country.
This is how I get the state field in the form:
$field = [
'type' => 'state',
'label' => 'State',
'required' => 1,
'class' => ['address-field form-row-first'],
'validate' => ['state']
];
woocommerce_form_field( 'billing_state', $field, '' );
The validation for the state field is done using the following snippet:
if (isset($_POST['billing_state']) && empty($_POST['billing_state']) ) {
$validation_errors->add('billing_state_error', __('Please enter your State', 'woocommerce'));
}
The validation works fine but I noticed that when a country like Netherlands is chosen, the state field disappears since Netherlands does not have any states. This is ok but when I click on the Sign Up button, the validation for state still runs even though the field is no longer there.
Would anyone know what change I will need to make in order to skip the validation for a field if it is hidden? Thank you.
Upvotes: 0
Views: 613
Reputation: 121
Well in this case you need ti check if that field is hidden or not
$(element).is(":hidden");
Then remove required from that field
$("#billing_state").removeAttr("required");
In your case you also need
var form = $('#my_form_id').get(0);
$.removeData(form,'validator');
Upvotes: 0
Reputation: 15620
The following would do it:
// Note: I assume the country field's "name" is billing_country. If not, just change it.
$country = wc_clean( wp_unslash( $_POST['billing_country'] ) );
// Here you should do the validation for the selected country...
$states = WC()->countries->get_states( $country );
$state = wc_clean( wp_unslash( $_POST['billing_state'] ) );
if ( is_array( $states ) && empty( $states ) ) {
// There are no states in the selected country, so do nothing.
} elseif ( is_array( $states ) && ! isset( $states[ $state ] ) ) {
// Either no state was selected or that it's not a valid state.
$validation_errors->add( 'invalid_billing_state', 'Please select a valid state.' );
} elseif ( empty( $state ) ) {
// For certain countries such as New Caledonia, state should be manually typed.
$validation_errors->add( 'empty_billing_state', 'Please enter a valid state.' );
}
Reference: See this file.
Upvotes: 1