user125264
user125264

Reputation: 1827

trying to validate string as boolean Coldfusion

I'm currently trying to validate if a string is exactly true or false as I'm building a spreadsheet importer using CF10.

My users will either enter in one of the following.

  1. NULL, which will equate to false
  2. TRUE which obviously equates to true
  3. FALSE which again will equate to false.

I'm trying to use the isValid('boolean',variable.data) to validate if the data is in fact a boolean string or not. However after reading quite a few posts I can see that it will validate true if its a positive number and false if it is a negative one etc.

I'm wondering if anyone has an easy fix to getting boolean validation working for strings easily ? Is this more a regular expressions scenario to make it work properly ?

Any help greatly appreciated.

Upvotes: 2

Views: 2077

Answers (3)

Leigh
Leigh

Reputation: 28873

Assuming you mean the literal string "NULL", one option is using list functions. Search a list of allowed values, ie "true,false,null". If the entry is found, it is valid:

<cfif listFindNoCase("true,false,null", theValue)>
    this is a valid boolean value
<cfelse>
    not found. do something here...
</cfif>

Then a simple string comparison would return false for everything other than the literal string "true":

  isTrue = compareNoCase(e, "true") eq 0 ? true : false`

Upvotes: 8

Adam Cameron
Adam Cameron

Reputation: 29870

If you need to evaluate whether a string is exactly "true" or "false", then you are not doing a boolean comparison, you are doing a string comparison.

So to that end, you'd be wanting to use compare() or compareNoCase() (depending on how rigid you need to be).

Upvotes: 4

Dale Fraser
Dale Fraser

Reputation: 4748

You could just do some logic or am I missing something.

<cfset booleanResult = enteredValue eq 'TRUE' ? true : false />

Upvotes: 0

Related Questions