Conditionally Unique Field

I 'd like to have a unique field, but the uniqueness depends on the docstatus, for example if my field name is sort_id and a submitted record exists where sort_id = 455 and that document is cancelled, no error should show, but creation of new records with the same sort_id should be prohibited.

How can I do this.

server script to implement such validation check