CFWheels Rule Validations
ColdFusion
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
rules
ValidatesRulesOf.cfc
base.css
index.cfm
readme.md

readme.md

ValidatesRulesOf

This plugin adds additional object validation rules to the model layers. There are 60 built-in validations that can be run, and most have multiple additional arguments. The benefit of using rules validation is you can very easily chain multiple rules to be tested on a single field. Many rules also have the ability to "autoFix" the input, meaning stripping out invalid values or reformatting the data. Error messages are built into the rules, so instead of having 1 generic error message the rule can return a customized error which helps users correct mistakes. You can also easily create your own rules in just a few lines of code to override or augment the built-in validations with your own custom logic or error messages.

Function Syntax

ValidatesRulesOf([ properties, rules, required, mutable, autoFix, default, defaultOnError, multiple, prefixLabel, sentence, when, condition, unless ])

Parameters

Parameter Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
rules string No List of rules to validate each property against.
required boolean No true If the property is required, if not and the field is empty the rules will be skipped (similar to wheel's AllowBlank).
mutable boolean No true If the rules can change the input value, this necessary for autoFix and default.
autoFix boolean No false If rules should first try to auto-correct the problem before throwing an error if the property is mutable. This is handy to help correct mistakes for users, but it can also result in silent mistakes, where the user entered a value that was corrected but they didn't know or want it changed.
default any No If no value is provided then the property is updated to this default value if the property is mutable.
defaultOnError boolean No true If an error occurs in validation and a default value is given, and the property is mutable, then the property will be changed to this value. This is useful as a failsafe.
prefixLabel boolean No true Prefix the error message with the property name, this is good when displaying error messages in a box above the form, however if you are displaying errors inline in the form then consider disabling this.
sentence boolean No true End the error message with a period "." to make it a sentence.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).


Validation Rules

Name AutoFix Parameters Description
alpha Yes Checks the property to be alpha (A-Z).
alphaNumeric Yes Checks the property to be alpha-numeric (A-Z0-9).
boolean Yes [booleanType=trueFalse] Checks the property is boolean, possible types are: trueFalse, yesNo, onOff, bit.
condition Yes condition
[conditionError]
Throws an error if the condition is true, the error message is customizable.
contains Yes contains
[caseSensitive=false]
[containsReplace]
[containsError]
Throws an error if the property contains a value, if you include [containsReplace] the value will be replaced with this and the error message is customizable.
country No [countryList] Checks the property matches one of the 2 char 200+ country codes, or specify your own list.
creditcardExpiry No Checks the property is a date in the future, which is what a valid credit card expiry date should be.
creditcardMod9 Yes ccType Checks the property matches creditcard Mod9 verification and that the card type matches the number.
creditcardNumber Yes Checks the property matches creditcard verification using CF isValid().
creditcardType Yes [cardTypes=3] Checks the property matches a list of possible credit card types, the types are
1= m,a,v,d
2= mc,am,vi,ds
3= mc,amex,visa,disc
4= mastercard,amex,visa,discover
date No [parseDate=false] Checks the property is a date, and can also try to parseDate() first.
dateRange No [dateMin]
[dateMax]
Checks the property is between the date ranges.
dollar Yes [dollarSign=true]
[allowNegative=true]
Checks the property is a dollar value like "$9.99" or "9.99" or "-9.99" depending on parameters.
ean No Checks the property could be an EAN number, however does not perform a MOD check.
email No Checks the property is an email, it returns more insightful error messages for incorrect email addresses.
fileName No [extension] Checks the property is a valid filename that doesn't have invalid characters and optionally that the file extension matches.
filter Yes [filter]
[filterAdd]
Filters the string against a list of swear words, racist or hateful words. You can provide your own list of words or add additional words. The restricted words are replaced with ****
float Yes Checks the property is a decimal numbers like 132.45
hexCode Yes Checks the property only contains hexidecimal letters (0-9) and letters (A-F)
htmlRestriction Yes [allowTags] Checks the property only contains a limited set of HTML tags which by default are: B, STRONG, EM, I, FONT, UL, OL, LI, BR, P, DIV, SPAN, ADDRESS
htmlSafe Yes Checks the property doesn't contain any really bad HTML tags which by default are: OBJECT, EMBED, SCRIPT, APPLET, META, LINK, FRAME, FRAMESET, IFRAME
htmlStrict Yes Checks the property doesn't contain any HTML tags at all.
integer Yes Checks the property is an integer (0-9)
isbn Yes Checks the property is an ISBN code
length Yes [length]
[min]
[max]
[lengthUnits=number]
Checks the property string length, similar to validatesLengthOf. length can also be a range like: "2-5"
listExclude Yes list
[delimiters=,]
[caseSensitive=false]
[multiList=false]
Checks the property matches a list of excluded values, throws an error if it matches.
listMatch Yes list
[delimiters=,]
[caseSensitive=false]
[multiList=false]
Checks the property matches a list of possible values.
listLength No [listLength]
[listMin]
[listMax]
[delimiters=,]
Checks the property list length. listLength can also be a range like: "2-5"
mask Yes mask
[maskError=normal]
Checks the property matches an input mask. "A" = Alpha, "X" = AlphaNumeric, "0" = Numeric, anything else matches itself. Examples postal code: "A0A-0A0" or phone number: "000-000-0000". maskError = "normal" gives a generic error message, "detailed" says exactly which character doesn't match.
mssql No dataType
[dataError=normal]
Checks the property against the value ranges that are storeable in SQL Server data types. Supported types are: Decimal, Float, Real, BigInt, Int, SmallInt, TinyInt, Money, SmallMoney, Numeric, Bit, DateTime, SmallDateTime, Text, NText, VarChar, NVarChar, Char, NChar.
name Yes Checks the property is a name, meaning letters, spaces and punctuations.
nameEmail No Checks the property is a full name and email address like: "Fred Flintstone"
notZero No Checks the property is not "0", simple check.
number Yes Checks the property is a number, which can be positive, negative and have decimals.
password No passwordType=standard
[verifyProperty]
[caseSensitive=false]
Checks the property matches a type of password. verifyProperty checks that the value of this property matches another property for password confirmation. "standard" = letters, numbers, underscore, hyphens. "withNumbers" = alpha numeric. "withSymbols" = alpha numeric + symbols.
postalCode Yes [postalDivider=" "]
[autoFormat=true]
Checks the property is a Canadian postal code, autoFormat will reformat the value.
province No [provinceList] Checks the property is a 2 char Canadian province from the list, or provide your own acceptable list.
range Yes range
[rangeType=number]
Checks the property is within the numeric range, such as 5-10. rangeType also accepts: dollar, decimal, number, year or your own custom type like feet or inches for better error messages.
sqlSafe No [sqlSafe]
[sqlKeywords]
Checks the property against 3 checks. "keywords" checks for DELETE, INSERT, SELECT, UPDATE, DROP, ALTER, CREATE, "functions" checks for function names, "escape" replaces all single quotes and SQL comments.
state No [stateList] Checks the property is a 2 char US State from the list, or provide your own acceptable list.
stateProvince No [stateList]
[provinceList]
Checks the property is a 2 char US State or 2 char Canadian Province from the lists, or provide your own acceptable lists.
string Yes [noSpaces=false] Checks the property is a string.
telephone Yes [telephone=phone]
[divider=-]
Checks the property is a telephone number, different number formats are:
phone= Any number 7-12 digits long
phoneExt = 999-999-9999 x9999 (extension is optional)
(phoneStrict7 = 999-9999
phoneStrict10 = 999-999-9999
telephoneFakes Yes [telephoneFakes]
[divider=-]
Checks the property is not an obviously fake telephone number like 000-000-0000, 333-333-3333, 123-456-7890, etc
text Yes Checks the property only contains printable characters.
upc Yes Checks the property is UPC product code, it also does a MOD check.
url Yes Checks the property is a URL.
userName No Checks the property only contains letters and numbers plus underscores or hyphens.
wordCount Yes [wordCount]
[wordMin]
[wordMax]
Checks the property string's word count is within the range, handy to use for contact forms instead of a specific character limit.
zipCode Yes [zipDivider=-]
[autoFormat=true]
Checks the property is a US 5 or 9 char zip code. autoFormat strips and reformats the input so it is perfectly consistent.
zipFakes Yes [zipFakes] Checks the property is not an obviously fake zip code like 11111, 12345, 99999, etc.
zipPostal Yes [zipDivider=-]
[postalDivider=" "]
[autoFormat=true]
Checks the property is a US 5 or 9 char zip code or Canadian Postal code. autoFormat strips and reformats the input so it is perfectly consistent.

Complex Data Rules

Name Parameters Description
array [length]
[min]
[max]
Checks the property is a CF Array, and checks the length of the array with the optional parameters
binary Checks the property is binary
object Checks the property is a CF Object
query Checks the property is a CF Query
structure Checks the property is a CF Structure
WDDX Checks the property is a WDDX string

No-Error Rules (for reformatting properties)

Name Parameters Description
case case Changes the property to upper or lower.
replace [caseSensitive=false] Changes the property with a series of find and replace statemets, just input the arguments as pairs of findX / replaceX or reFindX / reReplaceX like:
find1="small", replace1="big", find2="medium", replace2="huge"


Contribute!

If you make a good generic validation rule (or improve the ones included) please submit it to me to include in this plugin, send it to me on github or email it to me: jordanclark AT gmail.com


Notes

Built-in rules are stored in the /plugins/ValidatesRulesOf/rules/ folder, your own customized rules can be stored in /rules/ (on the same level as /models/ or /views/).

For kicks this plugin also replaces validatesLengthOf validation so it can return much better error messages. The replaced method also accepts the new argument prefixLabel, but it is defaulted to true.

<p>
    The plugin used to have a modified version of <code>validatesUniquenessOf</code> but those changes are not obsolete and the         code has been removed.
</p>


This plugin changes all validation methods behaviour

The validation of required="true" is very similar to validatesPresenceOf that is built into wheels and can't easily be disabled. Instead I've changed validation routines to only return 1 error message per property, I don't think more are useful to users.
To go back to the original behaviour change this setting in /config/settings.cfm: <cfset set( multipleValidationErrors=true )>


Configuration:

You can specify default values for validation, if not provided the defaults will be:

<!--- in your settings.cfm --->
<cfset set(
    functionName="validatesRulesOf"
,   required="true"
,   mutable="true"
,   autoFix="false"
,   defaultOnError="true"
,   stopOnError="true"
,   prefixLabel="true"
,   sentence="true"
,   message="is a required field that was skipped"
}>
<cfset set(
    functionName="validatesLengthOf"
,   prefixLabel="true"
}>


Usage Example:

<!--- in your model --->
<cfset validatesRulesOf(property="firstname,lastname",rules="length,name",length="2-25",required=true)>
<cfset validatesRulesOf(property="email",rules="length,email",length="6-50")>
<cfset validatesRulesOf(property="phone",rules="length,telephone",telephone="us-phone",max=20)>
<cfset validatesRulesOf(property="age",rules="integer,range",range="14-100",rangeType="years")>
<cfset validatesRulesOf(property="comment",rules="length,wordCount,htmlStrict",max=1000,wordCount=200)>


Uninstallation:

To uninstall this plugin, simply delete the /plugins/ValidatesRulesOf-X.X.zip file.

Credits

This plugin was created by Jordan Clark

To submit an issue or fork this plugin, visit the jordanclark/cfwheels-ValidatesRulesOf repository on GitHub.

Disclaimer

Remember that you use this at your own risk and I'm not responsible for anything. Please don't sue me :)