Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
/**
* Validate an object or structure according to the constraints rules.
*
* @target An object or structure to validate
* @fields The fields to validate on the target. By default, it validates on all fields
* @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation
* @locale The i18n locale to use for validation messages
* @excludeFields The fields to exclude from the validation
* @includeFields The fields to include in the validation
* @profiles If passed, a list of profile names to use for validation constraints
*
* @return cbvalidation.model.result.IValidationResult
*/
function validate()
/**
* Validate an object or structure according to the constraints rules and throw an exception if the validation fails.
* The validation errors will be contained in the `extendedInfo` of the exception in JSON format
*
* @target An object or structure to validate
* @fields The fields to validate on the target. By default, it validates on all fields
* @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation
* @locale The i18n locale to use for validation messages
* @excludeFields The fields to exclude from the validation
* @includeFields The fields to include in the validation
* @profiles If passed, a list of profile names to use for validation constraints
*
* @return The validated object or the structure fields that where validated
* @throws ValidationException
*/
function validateOrFail()
/**
* Retrieve the application's configured Validation Manager
*/
function getValidationManager()
username = {
required="true",
requiredMessage="Please enter the {field}",
size="6-8",
sizeMessage="The username must be between {min} and {max} characters"
}propertyName = {
// The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.
accepted : any value,
// The field must be alphanumeric ONLY
alpha : any value,
// discrete math modifiers
discrete : (gt,gte,lt,lte,eq,neq):value
// value in list
inList : list,
// max value
max : value,
// Validation method to use in the target object must return boolean accept the incoming value and target object
method : methodName,
// min value
min : value,
// range is a range of values the property value should exist in
range : eg: 1..10 or 5..-5,
// regex validation
regex : valid no case regex
// required field or not, includes null values
required : boolean [false],
// The field under validation must be present and not empty if the `anotherfield` field is equal to the passed `value`.
requiredIf : {
anotherfield:value, anotherfield:value
}
// The field under validation must be present and not empty unless the `anotherfield` field is equal to the passed
requiredUnless : {
anotherfield:value, anotherfield:value
}
// same as but with no case
sameAsNoCase : propertyName
// same as another property
sameAs : propertyName
// size or length of the value which can be a (struct,string,array,query)
size : numeric or range, eg: 10 or 6..8
// specific type constraint, one in the list.
type : (alpha,array,binary,boolean,component,creditcard,date,email,eurodate,float,GUID,integer,ipaddress,json,numeric,query,ssn,string,struct,telephone,url,usdate,UUID,xml,zipcode),
// UDF to use for validation, must return boolean accept the incoming value and target object, validate(value,target):boolean
udf = variables.UDF or this.UDF or a closure.
// Check if a column is unique in the database
unique = {
table : The table name,
column : The column to check, defaults to the property field in check
}
// Custom validator, must implement coldbox.system.validation.validators.IValidator
validator : path or wirebox id, example: 'mypath.MyValidator' or 'id:MyValidator'
}terms = { accepted = true }terms = { alpha = true }myField = { discrete = "gt:4" }
myField = { discrete = "eq:luis" }
myField = { discrete = "lte:1" }myField = { inList = "red,green,blue" }myField = { max = 25 }myField = { method = "methodName" }
function methodName( validationData, targetValue ){
return true;
}myField = { min = 8 }myField = { range = "1..5" }
myField = { range = "5..-5" }myField = { regex = "^(sick|vacation|disability)$" }myField = { required=true }
myField = { required=false }myField = {
requiredIf = {
field2 = "test",
field3 = "hello"
}
}myField = {
requiredUnless = {
field2 = "test",
field3 = "hello"
}
}myField = { sameAs = "otherField" }myField = { sameAs = "otherField" }myField = { size : 10 }
myFiedl = { size : "8..20" }myField = { type : "float" }myField = { udf = function( value, target ) { return true; } }
myField = { udf = (value,target) => true }myField = { unique = { table : "users", column : "username" } }myField = { validator = "UniqueValidator@cborm" }
/**
* Validate an object or structure according to the constraints rules.
*
* @target An object or structure to validate
* @fields The fields to validate on the target. By default, it validates on all fields
* @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation
* @locale The i18n locale to use for validation messages
* @excludeFields The fields to exclude from the validation
* @includeFields The fields to include in the validation
* @profiles If passed, a list of profile names to use for validation constraints
*
* @return cbvalidation.model.result.IValidationResult
*/
function validate()
/**
* Validate an object or structure according to the constraints rules and throw an exception if the validation fails.
* The validation errors will be contained in the `extendedInfo` of the exception in JSON format
*
* @target An object or structure to validate
* @fields The fields to validate on the target. By default, it validates on all fields
* @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation
* @locale The i18n locale to use for validation messages
* @excludeFields The fields to exclude from the validation
* @includeFields The fields to include in the validation
* @profiles If passed, a list of profile names to use for validation constraints
*
* @return The validated object or the structure fields that where validated
* @throws ValidationException
*/
function validateOrFail()
/**
* Retrieve the application's configured Validation Manager
*/
function getValidationManager()function saveUser( event, rc, prc ){
// create and populate a user object from an incoming form
var user = populateModel( entityNew("User") );
// validate model
prc.validationResults = validate( user );
if( prc.validationResults.hasErrors() ){
// show errors
}
else{
// save
}
}
function save( event, rc, prc ){
userService
.getOrFail( rc.id )
.populate()
.validateOrFail()
.save();
}/**
* Copyright since 2020 by Ortus Solutions, Corp
* www.ortussolutions.com
* ---
* The ColdBox validation results interface, all inspired by awesome Hyrule Validation Framework by Dan Vega
*/
import cbvalidation.models.result.*;
interface{
/**
* Add errors into the result object
* @error The validation error to add into the results object
* @error_generic IValidationError
*
* @return IValidationResult
*/
any function addError(required error);
/**
* Set the validation target object name
* @return IValidationResult
*/
any function setTargetName(required string name);
/**
* Get the name of the target object that got validated
*/
string function getTargetName();
/**
* Get the validation locale
*/
string function getValidationLocale();
/**
* has locale information
*/
boolean function hasLocale();
/**
* Set the validation locale
*
* @return IValidationResult
*/
any function setLocale(required string locale);
/**
* Determine if the results had error or not
* @fieldThe field to count on (optional)
*/
boolean function hasErrors(string field);
/**
* Clear All errors
* @return IValidationResult
*/
any function clearErrors();
/**
* Get how many errors you have
* @fieldThe field to count on (optional)
*/
numeric function getErrorCount(string field);
/**
* Get the Errors Array, which is an array of error messages (strings)
* @fieldThe field to use to filter the error messages on (optional)
*/
array function getAllErrors(string field);
/**
* Get an error object for a specific field that failed. Throws exception if the field does not exist
* @fieldThe field to return error objects on
*
* @return IValidationError[]
*/
array function getFieldErrors(required string field);
/**
* Get a collection of metadata about the validation results
*/
struct function getResultMetadata();
/**
* Set a collection of metadata into the results object
*
* @return IValidationResult
*/
any function setResultMetadata(required struct data);
}/**
* Copyright since 2020 by Ortus Solutions, Corp
* www.ortussolutions.com
* ---
* The ColdBox validation error interface, all inspired by awesome Hyrule Validation Framework by Dan Vega
*/
import cbvalidation.models.result.*;
interface {
/**
* Set the error message
* @messageThe error message
*/
IValidationError function setMessage( required string message );
/**
* Set the field
* @messageThe error message
*/
IValidationError function setField( required string field );
/**
* Set the rejected value
* @valueThe rejected value
*/
IValidationError function setRejectedValue( required any value );
/**
* Set the validator type name that rejected
* @validationTypeThe name of the rejected validator
*/
IValidationError function setValidationType( required any validationType );
/**
* Get the error validation type
*/
string function getValidationType();
/**
* Set the validator data
* @dataThe data of the validator
*/
IValidationError function setValidationData( required any data );
/**
* Get the error validation data
*/
string function getValidationData();
/**
* Get the error message
*/
string function getMessage();
/**
* Get the error field
*/
string function getField();
/**
* Get the rejected value
*/
any function getRejectedValue();
} // validate user object
prc.results = validateModel( target=user, constraints="sharedUser" );
// validate incoming form elements in the RC or request collection
prc.results = validateModel( target=rc, constraints="sharedUser" );Shared Constraints
validation = {
sharedConstraints = {
sharedUser = {
fName = {required=true},
lname = {required=true},
age = {required=true, max=18 }
metadata = {required=false, type="json"}
},
loginForm = {
username = {required=true}, password = {required=true}
},
changePasswordForm = {
password = {required=true,min=6}, password2 = {required=true, sameAs="password", min=6}
}
}
}validate( target, "sharedUser" );
validate( rc, "loginForm" );
validate( rc, "changePasswordForm" );var myConstraints = {
login = { required=true, size=6..10 },
password = { required=true, size=6..10 }
};
prc.results = validateModel( target=user, constraints=myConstraints );User.constraintsUser.signInConstraints// Define the field by name
// The contents are the constraints
fieldName1 = {
validator1 = validationData,
validator2 = validationData
},
fieldName2 = {
validator1 = validationData,
validator2 = validationData
}try{
validateOrFail( target );
service.save( target );
} catch( ValidationException e ){
return {
"error" : true,
"validationErrors" : deserializeJSON( e.extendedInfo )
};
}prc.results = validateModel(
target=user,
includeFields="username,password",
excludeFields="id"
);// sample REST API create user
function create( event, rc, prc ){
var validationResult = validate(
target = rc,
constraints = {
username : { required : true },
email : { required : true, type : "email" },
password : { required : true }
}
)
if ( !validationResult.hasErrors() ) {
UserService.createUser( rc.username, rc.email, rc.password );
prc.response.setData( UserService.readUser( username = rc.username ) );
} else {
prc.response
.setError( true )
.addMessage( validationResult.getAllErrors() )
.setStatusCode( STATUS.BAD_REQUEST )
.setStatusText( "Validation error" );
}
}

validation = {
// The third-party validation manager to use, by default it uses CBValidation.
manager = "class path",
// You can store global constraint rules here with unique names
sharedConstraints = {
name = {
field = { constraints here }
}
}
}component persistent="true"{
// Object properties
property name="id" fieldtype="id" generator="native" setter="false";
property name="fname";
property name="lname";
property name="email";
property name="username";
property name="password";
property name="age";
// Validation
this.constraints = {
// Constraints go here
}
}component persistent="true"{
...
// Validation
this.constraints = {
fname = { required = true },
lname = { required = true},
username = {required=true, size="6..10"},
password = {required=true, size="6..8"},
email = {required=true, type="email"},
age = {required=true, type="numeric", min=18}
};
}validate( myUser );
validateOrFail( myUser );// get reference
property name="validationManager" inject="ValidationManager@cbvalidation";box install cbormthis.constraintProfiles = {
"new" = "fname,lname,email,password",
"update" = "fname,lname,email",
"passUpdate" = "password,confirmpassword"
}var results = validateModel( target=model, profiles="update" )
var results = validateModel( target=model, profiles="update,passUpdate" ){
fieldName : { validator: "UniqueValidator@cborm" },
// or
fieldName : { "UniqueValidator@cborm" : {} }
}this.constraints = {
"username" = { required=true, validator: "UniqueValidator@cborm" },
"email" = { required=true, validator: "UniqueValidator@cborm" }
};<-- Display all errors as a message box --->
#getInstance( "MessageBox@cbMessagebox" )
.renderMessage( type="error", messageArray=prc.validationResults.getAllErrors() )#<cfif prc.validationResults.hasErrors()>
<ul>
<cfloop array="#prc.validationResults.getErrors()#" index="thisError">
<li>#thisError.getMessage()#</li>
</cfloop>
</ul>
</cfif>validation = {
// The third-party validation manager to use, by default it uses CBValidation.
manager = "my.class.path"
}{constraintName}Message = "My Custom Message";username = {
required="true",
requiredMessage="Please enter the username",
size="6-8",
sizeMessage="The username must be between 6 to 8 characters"
}slug : {
required : true,
udf : ( value, target ) => {
if( isNull( arguments.value ) ) return false;
return qb.from( "content" )
.where( "slug", arguments.value )
.when( this.isLoaded(), ( q ) => {
arguments.q.whereNotIn( "id", this.getId() );
} )
.count() == 0;
}
},/**
* Copyright since 2020 by Ortus Solutions, Corp
* www.ortussolutions.com
* ---
* The ColdBox validator interface, all inspired by awesome Hyrule Validation Framework by Dan Vega
*/
interface {
/**
* Will check if an incoming value validates
* @validationResultThe result object of the validation
* @targetThe target object to validate on
* @fieldThe field on the target object to validate on
* @targetValueThe target value to validate
* @rules The rules imposed on the currently validating field
*/
boolean function validate(
required any validationResult,
required any target,
required string field,
any targetValue,
any validationData,
struct rules
);
/**
* Get the name of the validator
*/
string function getName();
}/**
* Copyright since 2020 by Ortus Solutions, Corp
* www.ortussolutions.com
* ---
* This validator validates if a value is is less than a maximum number
*/
component accessors="true" singleton {
property name="name";
/**
* Constructor
*/
MaxValidator function init(){
variables.name = "Max";
return this;
}
/**
* Will check if an incoming value validates
* @validationResultThe result object of the validation
* @targetThe target object to validate on
* @fieldThe field on the target object to validate on
* @targetValueThe target value to validate
* @validationDataThe validation data the validator was created with
*/
boolean function validate(
required any validationResult,
required any target,
required string field,
any targetValue,
any validationData,
struct rules
){
// return true if no data to check, type needs a data element to be checked.
if ( isNull( arguments.targetValue ) || ( isSimpleValue( arguments.targetValue ) && !len( arguments.targetValue ) ) ) {
return true;
}
// Max Tests
if ( arguments.targetValue <= arguments.validationData ) {
return true;
}
var args = {
message : "The '#arguments.field#' value is not less than or equal to #arguments.validationData#",
field : arguments.field,
validationType : getName(),
rejectedValue : ( isSimpleValue( arguments.targetValue ) ? arguments.targetValue : "" ),
validationData : arguments.validationData
};
var error = validationResult.newError( argumentCollection = args ).setErrorMetadata( { max : arguments.validationData } );
validationResult.addError( error );
return false;
}
/**
* Get the name of the validator
*/
string function getName(){
return variables.name;
}
}//sample custom validator constraints
this.constraints = {
// Approach #1
myField = {
required : true,
validator : "MyCustomID"
},
// Approach #2
myField2 = {
required : true,
UniqueInMyDatabase : {
column : "column_name",
table : "table_name",
dsn : "myDatasource"
},
MyTimezoneValidator : true
}
};{ObjectName}.{Field}.{ConstraintType}}=Message{SharedConstraintName}.{Field}.{ConstraintType}=MessageGenericForm.{Field}.{ConstraintType}=Messageblank=The field {property} must contain a value.
email=The field {property} is not a valid email address.
unique=The field {property} is not a unique value.
size=The field {property} was not in the size range of {size}.
inlist=The field {property} was not in the list of possible values.
validator=There was a problem with {property}.
min=The minimum value {min} was not met for the field {property}.
max=The maximum value {max} was exceeded for the field {property}.
range=The range was not met for the field {property}.
matches=The field {property} does not match {regex}.
numeric=The field {property} is not a valid number.