CRM-13554 - Improve string validation in the query engine

Backport of https://github.com/civicrm/civicrm-core/pull/1758