This doesn't work because it can't cast JSONB to 'bytea'. I tried casting to 'text', still no luck. Could anyone please help me?
You can use check-constraint like this:
# create table t (
jb jsonb
);
# alter table t add constraint jb_length_check CHECK (length(jb::text) < 16); -- 16 is example value
# insert into t values ('{"key":"v"}');
INSERT 0 1
# insert into t values ('{"key":"value"}');
ERROR: new row for relation "t" violates check constraint "jb_length_check"
DETAIL: Failing row contains ({"key": "value"}).
Also, is there a better approach to impose a size limit, then writing triggers? I need it to be fairly flexible, e.g. 10Kb is not a constant, it may even be different for different documents (rows) in the same table.
The better approach is extract your length-validation logic into your application.