Skip to content

Commit

Permalink
Add #valid, #invalid_message, #invalid_count options on elements.
Browse files Browse the repository at this point in the history
Add comment about how to express validators and check validity in the
front-end.

Add .wp-form-element-invalid class to invalid elements when rendering.

Increment $form['#invalid_count'] for each invalid element found in
processing.
  • Loading branch information
Ben Doherty committed Mar 18, 2016
1 parent c030765 commit c12c937
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions inc/class-wp-forms-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ class WP_Forms_API {
// Validation schema for this element. Can be an function or regular expression.
'#validator' => null,

// Validity state of this element.
'#valid' => true,

// The message to show after invalid values
'#invalid_message' => 'Invalid value',

// How many invalid elements were found in this form.
'#invalid_count' => 0,

// When #type=multiple, the index of this particular element in the set
'#index' => null,

Expand Down Expand Up @@ -690,6 +699,18 @@ static function render_element( $element, &$values, $form = null ) {
}
}

if( !$element['#valid'] ) ) {
$element['class'][] = 'wp-form-element-invalid';
}

if( $element['#validator'] ) {
// TODO: how to express this to markup so that it can be used in
// validation post-backs? Perhaps it's better to take the drupal approach
// and post the whole form, check output, and re-render it with validation
// messages.
}


$element = apply_filters( 'wp_form_element', $element );
$element = apply_filters( 'wp_form_element_key_' . $element['#key'], $element );

Expand All @@ -716,6 +737,11 @@ static function render_element( $element, &$values, $form = null ) {
$markup .= $element['#label_position'] == 'after' ? $label : '';
}

// Add validation message if element value is not valid
if( !$element['#valid'] ) && $element['#invalid_message'] ) {
$markup .= self::make_tag( 'span', array( 'class' => 'wp-form-element-invalid-message' ), $element['#invalid_message'] );
}

if( $element['#description'] ) {
$markup .= self::make_tag( 'p', array( 'class' => 'description' ), $element['#description'] );
}
Expand Down Expand Up @@ -937,6 +963,7 @@ static function process_element( $element, &$values, &$input ) {

// STOP! In the name of ... invalidity!
if( !$element['#valid'] ) {
$element['#form']['#invalid_count'] ++;
break;
}
}
Expand Down

0 comments on commit c12c937

Please sign in to comment.