some improvements

1. check invalid characters
2. check invalid string length
3. reduct redundant code to clarify the logic