def validate(self, val):
if not isinstance(val, six.string_types):<EOL><INDENT>raise ValidationError("<STR_LIT>"<EOL>% (val, generic_type_name(val)))<EOL><DEDENT>if not six.PY3 and isinstance(val, str):<EOL><INDENT>try:<EOL><INDENT>val = val.decode('<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>raise ValidationError("<STR_LIT>")<EOL><DEDENT><DEDENT>if self.max_length is not None and len(val) > self.max_length:<EOL><INDENT>raise ValidationError("<STR_LIT>"<EOL>% (val, self.max_length, len(val)))<EOL><DEDENT>if self.min_length is not None and len(val) < self.min_length:<EOL><INDENT>raise ValidationError("<STR_LIT>"<EOL>% (val, self.min_length, len(val)))<EOL><DEDENT>if self.pattern and not self.pattern_re.match(val):<EOL><INDENT>raise ValidationError("<STR_LIT>"<EOL>% (val, self.pattern))<EOL><DEDENT>return val<EOL>
A unicode string of the correct length and pattern will pass validation.
In PY2, we enforce that a str type must be valid utf-8, and a unicode
string will be returned.