Thursday, December 12, 2013

Sapphire 0.7 : Use EL for Validation

The new @Validation annotation allows an expression to be used to define a validation rule rather than implementing a custom ValidationService. This leads to a model that is easier to understand and maintain.

@Type( base = BigDecimal.class )
@DefaultValue( text = "0" )
@NumericRange( min = "0" )
    
@Validation
(
    rule = "${ Discount <= Subtotal + Delivery }",
    message = "Discount must not exceed subtotal plus delivery charge."
)

ValueProperty PROP_DISCOUNT = new ValueProperty( TYPE, "Discount" );

Value<BigDecimal> getDiscount();
void setDiscount( String value );
void setDiscount( BigDecimal value );

Multiple rules can be specified by using @Validations annotation, the message can be formulated using an expression, and the optional severity attribute allows the developer to make a rule failure either an error or a warning.

@Validations
(
    {
        @Validation
        (
            rule = "${ Path == null || Path.StartsWith( '/' ) }",
            message = "Path \"${ Path }\" must start with a slash."
        ),
        @Validation
        (
            rule = "${ Path == null || Path.StartsWith( HomePath ) }",
            message = "Path \"${ Path }\" is not within the home folder.",
            severity = Status.Severity.WARNING
        )
    }
)

ValueProperty PROP_PATH = new ValueProperty( TYPE, "Path" );

Value<String> getPath();
void setPath( String value );

No comments: