Skip Navigation

[Resolved] Split: How to validate numeric fields within a certain range

This support ticket is created 6 years ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 1 reply, has 2 voices.

Last updated by Nigel 6 years ago.

Assisted by: Nigel.

Author
Posts
#1185796

I have several number fields in a form that should have restricted ranges, e.g. 1-5, 6-10, 11-20, 21-99

How to implement?

#1185855

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Screenshot 2019-01-17 at 11.14.00.png

Hi Ramon

You could aim for validation in the browser (the user cannot even try to submit the form if a number is out-of-range), and/or you could apply validation on the server, whereby the form is submitted but rejected if the field values are invalid.

The first is pretty straightforward in principle.

The number input type accepts min and max arguments: hidden link

But, we don't have any way for you to add such arguments to the input markup generated by the form.

You can update the input type from text to number and apply the range values with a little JavaScript.

On my test site I have a number field with slug "low-value" so the actual meta key for this field including Types prefix is "wpcf-low-value", so I can add the following custom JS to the Form and it will update the field input to give the kind of result you see in the screenshot (browser-based validation).

( function( $ ) {
	$( document ).ready( function(){
		$('input[name="wpcf-low-number"]').attr( {"type":"number","min":"0","max":"5"});
		// add more adjustments to other fields are required
	});
})( jQuery );

If you wanted to include server-side validation then you would need to use the cred_form_validate hook (https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate).