Skip to content
41 changes: 39 additions & 2 deletions classes/models/fields/FrmFieldNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,43 @@ protected function extra_field_opts() {
*/
protected function add_extra_html_atts( $args, &$input_html ) {
$this->add_min_max( $args, $input_html );

if ( ! $this->uses_default_invalid_message() ) {
return;
}

$input_html .= ' data-minmsg="' . esc_attr( $this->get_min_error_message() ) . '"';
$input_html .= ' data-maxmsg="' . esc_attr( $this->get_max_error_message() ) . '"';
}

/**
* A custom invalid message keeps showing for a value outside the range in JS validation.
*
* @since x.x
*
* @return bool
*/
private function uses_default_invalid_message() {
$invalid = FrmField::get_option( $this->field, 'invalid' );
return '' === $invalid || FrmFieldsHelper::default_invalid_msg( $this->field ) === $invalid;
}

/**
* @since x.x
*
* @return string
*/
private function get_min_error_message() {
return __( 'Please select a higher number', 'formidable' );
}

/**
* @since x.x
*
* @return string
*/
private function get_max_error_message() {
return __( 'Please select a lower number', 'formidable' );
}

/**
Expand All @@ -91,9 +128,9 @@ public function validate( $args ) {
$maxnum = FrmField::get_option( $this->field, 'maxnum' );

if ( $minnum !== '' && $value < $minnum ) {
$errors[ 'field' . $args['id'] ] = __( 'Please select a higher number', 'formidable' );
$errors[ 'field' . $args['id'] ] = $this->get_min_error_message();
} elseif ( $maxnum !== '' && $value > $maxnum ) {
$errors[ 'field' . $args['id'] ] = __( 'Please select a lower number', 'formidable' );
$errors[ 'field' . $args['id'] ] = $this->get_max_error_message();
}

$this->validate_step( $errors, $args );
Expand Down
2 changes: 1 addition & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ export default [
},
},
{
files: [ 'tests/js/style-live-preview.test.mjs', 'tests/js/paypalBootstrap.test.mjs', 'tests/js/inlineSubmitAlignment.test.mjs', 'tests/js/squareVerifyBuyer.test.mjs', 'tests/js/invisibleRecaptcha.test.mjs', 'tests/js/productFieldChange.test.mjs' ],
files: [ 'tests/js/style-live-preview.test.mjs', 'tests/js/paypalBootstrap.test.mjs', 'tests/js/inlineSubmitAlignment.test.mjs', 'tests/js/squareVerifyBuyer.test.mjs', 'tests/js/invisibleRecaptcha.test.mjs', 'tests/js/productFieldChange.test.mjs', 'tests/js/numberRangeValidation.test.mjs' ],
rules: {
// The harnesses execute only checked-in scripts.
'sonarjs/code-eval': 'off',
Expand Down
26 changes: 20 additions & 6 deletions js/formidable.js
Original file line number Diff line number Diff line change
Expand Up @@ -988,14 +988,28 @@ function frmFrontFormJS() {
* @return {void}
*/
function checkNumberField( field, errors ) {
let fieldID;
const number = field.value;

if ( number !== '' && isNaN( number / 1 ) !== false ) {
fieldID = getFieldId( field, true );
if ( ! ( fieldID in errors ) ) {
errors[ fieldID ] = getFieldValidationMessage( field, 'data-invmsg' );
}
if ( number === '' ) {
return;
}

let messageType = '';
if ( isNaN( number / 1 ) !== false ) {
messageType = 'data-invmsg';
} else if ( field.validity?.rangeUnderflow ) {
messageType = 'data-minmsg';
} else if ( field.validity?.rangeOverflow ) {
messageType = 'data-maxmsg';
}

if ( ! messageType ) {
return;
}

const fieldID = getFieldId( field, true );
if ( ! ( fieldID in errors ) ) {
errors[ fieldID ] = getFieldValidationMessage( field, messageType ) || getFieldValidationMessage( field, 'data-invmsg' );
}
}

Expand Down
3 changes: 1 addition & 2 deletions js/formidable.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 67 additions & 0 deletions tests/js/numberRangeValidation.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import { runInNewContext } from 'node:vm';

const source = readFileSync( new URL( '../../js/formidable.js', import.meta.url ), 'utf8' );

/**
* Run JavaScript validation for a form holding one number field.
*
* @param {string} value The typed value.
* @param {Object} validity The field's ValidityState flags.
* @param {Object} attrs The field's data attributes.
* @return {string|undefined} The error for the field.
*/
function getNumberErrors( value, validity, attrs ) {
const field = {
type: 'number',
name: 'item_meta[12]',
value,
validity: { valid: ! Object.values( validity ).includes( true ), ...validity },
pattern: null,
classList: { contains: () => false },
getAttribute: name => attrs[ name ] ?? null
};
const form = {
classList: { contains: () => false },
querySelector: () => null,
querySelectorAll: selector => selector === 'input,select,textarea' ? [ field ] : []
};
function jQuery() {
return { ready() {}, hasClass: () => true, querySelectorAll: () => [] };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unexpected empty method 'ready'


Having empty functions hurts readability, and is considered a code-smell. There's almost always a way to avoid using them. If you must use one, consider adding a comment to inform the reader of its purpose.

}
const context = {
window: {},
document: { body: { classList: { contains: () => false } }, dispatchEvent() {} },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unexpected empty method 'dispatchEvent'


Having empty functions hurts readability, and is considered a code-smell. There's almost always a way to avoid using them. If you must use one, consider adding a comment to inform the reader of its purpose.

jQuery,
CustomEvent() {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unexpected empty method 'CustomEvent'


Having empty functions hurts readability, and is considered a code-smell. There's almost always a way to avoid using them. If you must use one, consider adding a comment to inform the reader of its purpose.

};

runInNewContext( source, context );
context.frmFrontForm = context.window.frmFrontForm;

return context.window.frmFrontForm.getAjaxFormErrors( form )[ 12 ];
}

const attrs = {
'data-invmsg': 'Enter a number',
'data-minmsg': 'Please select a higher number',
'data-maxmsg': 'Please select a lower number'
};

test( 'A number below the minimum shows the minimum message', () => {
assert.equal( getNumberErrors( '1', { rangeUnderflow: true }, attrs ), 'Please select a higher number' );
} );

test( 'A number above the maximum shows the maximum message', () => {
assert.equal( getNumberErrors( '5000', { rangeOverflow: true }, attrs ), 'Please select a lower number' );
} );

test( 'A number within range has no error', () => {
assert.equal( getNumberErrors( '10', {}, attrs ), undefined );

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove redundant `undefined` from function call


When an argument is omitted from a function call, it will default to undefined. It is therefore redundant to explicitly pass an undefined literal as the last argument.

} );

test( 'A range failure without range messages falls back to the invalid message', () => {
assert.equal( getNumberErrors( '1', { rangeUnderflow: true }, { 'data-invmsg': 'Enter a number' } ), 'Enter a number' );
} );
48 changes: 48 additions & 0 deletions tests/phpunit/fields/test_FrmFieldNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,54 @@ public function test_add_min_max_step() {
$this->assertStringContainsString( 'step="0.5"', $this->get_min_max_html( array( 'step' => '0.5' ) ) );
}

/**
* @covers FrmFieldNumber::add_extra_html_atts
*/
public function test_add_extra_html_atts_includes_range_messages() {
$number = new FrmFieldNumber(
array(
'id' => 0,
'type' => 'number',
'field_options' => array(),
)
);
$input_html = '';
$this->run_private_method( array( $number, 'add_extra_html_atts' ), array( array(), &$input_html ) );

$this->assertStringContainsString( 'data-minmsg="Please select a higher number"', $input_html );
$this->assertStringContainsString( 'data-maxmsg="Please select a lower number"', $input_html );
}

/**
* @covers FrmFieldNumber::add_extra_html_atts
*/
public function test_add_extra_html_atts_skips_range_messages_for_custom_invalid_message() {
$number = new FrmFieldNumber(
array(
'id' => 0,
'type' => 'number',
'field_options' => array( 'invalid' => 'Numbers only' ),
)
);
$input_html = '';
$this->run_private_method( array( $number, 'add_extra_html_atts' ), array( array(), &$input_html ) );

$this->assertStringNotContainsString( 'data-minmsg', $input_html );
$this->assertStringNotContainsString( 'data-maxmsg', $input_html );

$number = new FrmFieldNumber(
array(
'id' => 0,
'type' => 'number',
'field_options' => array( 'invalid' => FrmFieldsHelper::default_invalid_msg( array( 'type' => 'number' ) ) ),
)
);
$input_html = '';
$this->run_private_method( array( $number, 'add_extra_html_atts' ), array( array(), &$input_html ) );

$this->assertStringContainsString( 'data-minmsg', $input_html );
}

/**
* @param array $options
*
Expand Down
Loading