Is there a recommended way to represent booleans in HTML form hidden fields?
Is it usually a matter of existence, or should one use 1/0 or "true"/"false" strings?
Is there a recommended way to represent booleans in HTML form hidden fields?
Is it usually a matter of existence, or should one use 1/0 or "true"/"false" strings?
That logic can be implemented with monkey patching of variable according to it's string value. In that case recommended way of identifying Boolean value depends on how that values are treated by server side. See monkey patching example in Ruby.
However you can avoid monkey patching with approach below:
Most likely all servers would work well with 'true'
value to represent True (actually there are no matter as long as you work directly with string, but for convention it's clearly understandable) and empty string''
to represent False (because empty string ''
would be treated as false in most cases, to do that you can define input[type=hidden] as placeholder of hidden value and assign corresponding value.
To define hidden input with Falsy value you have to set value
attribute to empty string ''
, all other values would be treated as Truly.
<input type="hidden" name="is-truly" value="">
In that way most likely request.POST['is-truly']
value on the server would be treated as False ( because empty string ''
is Falsy, but you have to double check that on server side)
NOTE: It's not recommended to use eval to verify variable type.
Would be useful if you are using PHP:
test.php?test=false (constructed with http_build_query( array( 'test'=>'false' ) )
):
var_dump( $_REQUEST['test'] ); //string(5) "false"
var_dump( (bool)$_REQUEST['test'] ); //bool(true)
var_dump( $_REQUEST['test'] == FALSE ); //bool(false)
var_dump( $_REQUEST['test'] == "false" ); //bool(true)
--
test.php?test=0 (constructed with http_build_query( array( 'test'=>FALSE ) )
):
var_dump( $_REQUEST['test'] ); //string(1) "0"
var_dump( (bool)$_REQUEST['test'] ); //bool(false)
var_dump( $_REQUEST['test'] == FALSE ); //bool(true)
© 2022 - 2024 — McMap. All rights reserved.
$_POST
array even when empty so testing for existence (like withisset
) wouldn't help there, you would either have to remove the field before form submission or have the server side script test for empty instead of existence. Not sure about other languages though. – Nolantrue
to mark boolean true. – Ribwort