andy mccullough
andy mccullough

Reputation: 9571

Is it good practice to rely on domain constraints for validation

Is it good practice to validate user input using the domain constraints such as email(unique:true) then rely on a message.properties input such as className.email.unique=Email address already in use to create an error message. Or is it better practice to have some client side validation or some check being carried in a web service before trying to persist to the domain?

Upvotes: 0

Views: 138

Answers (2)

dellyjm
dellyjm

Reputation: 426

You should look into using CommandObjects on your controller action when accepting request payload.

http://grails.org/doc/latest/guide/single.html#commandObjects

Command Objects allow you to put validation rules/constraints on the request payload. Now this is good because you apply new constraints which are specific to payload request from web without causing it to hit your logic. A cool feature is you can inherit domain constraints.

@grails.validation.Validateable
class LoginCommand {
    String username
    String password
    static constraints = {
       username(blank: false, minSize: 6)
       password(blank: false, minSize: 6)
    }
}

Upvotes: 0

alexandercannon
alexandercannon

Reputation: 544

It common practise to use both client and server sides.

Client side validation adds convenience to the user and can reduce bandwidth or improve the work flow but it isn't 100% reliable.

Client side validation has significant aesthetic appeal as well as being able to alert users of mistakes before the post operation, it will look better but and be nice for users but won't stop bad inputs, it is purely an aesthetic choice for improving how the user interacts with the page and hopefully reducing the bandwidth of sending multiple bad inputs before getting it right.

The source of a page can be edited locally in order to disable or bypass even the most well formed validation and to completely suppress it, so nothing you can do on the client side will be able to stop a determined user from making a mess of your system.

This means you also need to have good server side validation, it is good practise to try and protect yourself against injections and other sorts of nonsense users can intentionally or accidentally pull off, especially since you are out on the web. Reducing the points of failure by having both validations is the preferred way because they both add value.

Upvotes: 2

Related Questions