Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
prc.results = validateModel( target=user, fields="login,password" );{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"
} // 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" );// get reference
property name="validationManager" inject="ValidationManager@cbvalidation";myConstraints = {
login = { required=true, size=6..10 },
password = { required=true, size=6..10 }
};
prc.results = validateModel( target=user, constraints=myConstraints );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}
}
}
}ValidationManager@cbvalidationbox install cbormvalidate( target, "sharedUser" );
validate( rc, "loginForm" );
validate( rc, "changePasswordForm" );/**
* 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 in the validation
*
* @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
*
* @return The validated object or the structure fields that where validated
* @throws ValidationException
*/
function validateOrFail(){
return getValidationManager().validateOrFail( argumentCollection=arguments );
}
/**
* Retrieve the application's configured Validation Manager
*/
function getValidationManager(){ fieldName : { validator: "UniqueValidator@cborm" } }this.constraints = {
"username" = { required=true, validator: "UniqueValidator@cborm" },
"email" = { required=true, validator: "UniqueValidator@cborm" }
};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}
};
}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 }
}
}
}User.constraintsUser.signInConstraintsvalidate( myUser );// 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" );
}
}{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.username = {
required="true",
requiredMessage="Please enter the {field}",
size="6-8",
sizeMessage="The username must be between {min} and {max} characters"
}<-- 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>try{
validateOrFail( target );
service.save( target );
} catch( ValidationException e ){
return {
"error" : true,
"validationErrors" : deserializeJSON( e.extendedInfo )
};
}{}//sample custom validator constraints
this.constraints = {
myField = {
UniqueInDB = {
table= "table_name",
column = 'column_name'
}
}
};field : The field or property in the object that is in validation/**
* Will check if an incoming value validates
* @validationResult.hint The result object of the validation
* @target.hint The target object to validate on
* @field.hint The field on the target object to validate on
* @targetValue.hint The target value to validate
*/
boolean function validate(required cbvalidation.models.result.IValidationResult validationResult, required any target, required string field, any targetValue, any validationData);
/**
* Get the name of the validator
*/
string function getName();//sample validator
/**
* UniqueInDB validator. This checks and returns fals if value is already present in DB
*/
component singleton implements="cbvalidation.models.validators.IValidator" accessors="true" {
/**
* Constructor
*/
UniqueInDB function init(){
variables.Name = "UniqueInDBValidator";
return this;
}
/**
* validate
*/
boolean function validate(
required cbvalidation.models.result.IValidationResult validationResult,
required any target,
required string field,
any targetValue,
any validationData
){
//check validationdata
if ( !IsStruct(validationData ) ) {
throw(message="The validator data is invalid: #arguments.validationData#, it must be a struct with keys 'table' = 'tableName' and 'column' = 'columnName'");
}
//check validationdata
if ( !structKeyExists(validationData,"table") || !structKeyExists(validationData,"column") ) {
throw(message="The validator data is invalid: #serializeJSON(validationData)# it must be a struct with keys 'table' = 'tableName' and 'column' = 'columnName'");
}
var myParams = { table =validationData.table, column=validationData.column, columnvalue=targetValue };
var sql = "Select #validationData.column# from #validationData.table# where #validationData.column# = :columnvalue";
var myQuery = queryExecute(sql, myParams);
// This sample only validates NEW records, additional code is necessary for EDITING existing records
if (myQuery.recordcount == 0) {
return true
}
// error messages definieren
var args = {
message="The value #targetValue# is not unique in your database",
field=arguments.field,
validationType=getName(),
validationData=arguments.validationData
};
var error = validationResult.newError(argumentCollection=args).setErrorMetadata({table=validationData.table, column=validationData.column});
validationResult.addError( error );
return false;
}
/**
* getName
*/
string function getName(){
return variables.Name
}
}/**
********************************************************************************
Copyright Since 2005 ColdBox Framework by Luis Majano and Ortus Solutions, Corp
www.coldbox.org | www.luismajano.com | www.ortussolutions.com
********************************************************************************
The ColdBox validator interface, all inspired by awesome Hyrule Validation Framework by Dan Vega
*/
component accessors="true" implements="cbvalidation.models.validators.IValidator" singleton{
property name="name";
MaxValidator function init(){
name = "Max";
return this;
}
/**
* Will check if an incoming value validates
* @validationResult.hint The result object of the validation
* @target.hint The target object to validate on
* @field.hint The field on the target object to validate on
* @targetValue.hint The target value to validate
* @validationData.hint The validation data the validator was created with
*/
boolean function validate(required cbvalidation.models.result.IValidationResult validationResult, required any target, required string field, any targetValue, string validationData){
// Simple Tests
if( !isNull(arguments.targetValue) AND arguments.targetValue <= arguments.validationData ){
return true;
}
var args = {message="The '#arguments.field#' value is not less than #arguments.validationData#",field=arguments.field,validationType=getName(),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 name;
}
}
propertyName = {
// required field or not, includes null values
required : boolean [false],
// specific type constraint, one in the list.
type : (ssn,email,url,alpha,boolean,date,usdate,eurodate,numeric,GUID,UUID,integer,string,telephone,zipcode,ipaddress,creditcard,binary,component,query,struct,json,xml),
// size or length of the value which can be a (struct,string,array,query)
size : numeric or range, eg: 10 or 6..8
// 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
// same as another property
sameAs : propertyName
// same as but with no case
sameAsNoCase : propertyName
// value in list
inList : list
// value is unique in the database via the cborm module, it must be installed
unique : true
// discrete math modifiers
discrete : (gt,gte,lt,lte,eq,neq):value
// 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.
// Validation method to use in the target object must return boolean accept the incoming value and target object
method : methodName
// Custom validator, must implement coldbox.system.validation.validators.IValidator
validator : path or wirebox id, example: 'mypath.MyValidator' or 'id:MyValidator'
// min value
min : value
// max value
max : value
}/**
* 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 in the validation
*
* @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
*
* @return The validated object or the structure fields that where validated
* @throws ValidationException
*/
function validateOrFail(){
return getValidationManager().validateOrFail( argumentCollection=arguments );
}
/**
* 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
}
}interface{
/**
* Add errors into the result object
* @error.hint The validation error to add into the results object
*/
IValidationResult function addError(required IValidationError error);
/**
* Set the validation target object name
*/
IValidationResult function setTargetName(required string name);
/**
* Get the name of the target object that got validated
*/
string function getTargetName();
/**
* Get the locale
*/
string function getLocale();
/**
* has locale information
*/
boolean function hasLocale();
/**
* Set the validation locale
*/
IValidationResult function setLocale(required string locale);
/**
* Determine if the results had error or not
* @field.hint The field to count on (optional)
*/
boolean function hasErrors(string field);
/**
* Clear All errors
*/
IValidationResult function clearErrors();
/**
* Get how many errors you have
* @field.hint The field to count on (optional)
*/
numeric function getErrorCount(string field);
/**
* Get the Errors Array, which is an array of error messages (strings)
* @field.hint The 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
* @field.hint The field to return error objects on
*/
IValidationError[] 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
*/
IValidationResult function setResultMetadata(required struct data);
}/**
* Set error metadata that can be used in i18n message replacements or in views
* @data.hint The name-value pairs of data to store in this error.
*/
IValidationError function setErrorMetadata(required any data);
/**
* Get the error metadata
*/
struct function getErrorMetadata();
/**
* Set the error message
* @message.hint The error message
*/
IValidationError function setMessage(required string message);
/**
* Set the field
* @message.hint The error message
*/
IValidationError function setField(required string field);
/**
* Set the rejected value
* @value.hint The rejected value
*/
IValidationError function setRejectedValue(required any value);
/**
* Set the validator type name that rejected
* @validationType.hint The name of the rejected validator
*/
IValidationError function setValidationType(required any validationType);
/**
* Get the error validation type
*/
string function getValidationType();
/**
* Set the validator data
* @data.hint The 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();