javascript - Warn on non-ASCII Characters in Django Form -
i'm trying add client-side ajax validation of django form. want warn users, typing in field, if of characters inputted not ascii.
i put basic python check ascii characters in form's clean method. don't want that, though, don't want produce error rather give warning message , let user continue rest of form.
try: field_value.decode('ascii') except unicodeencodeerror: #raise forms.validationerror("non-ascii characters may cause issues in registering data. consider removing these characters. may still submit @ own risk.") # want show warning user can still submit form if wish i want show small warning under field user typing. i've tried using django-dajax, not sure. how can this?
edit: clarify, want show warning before user submits form. so, filling out form...
use javascript validate form field.
example (using jquery):
<form> <input name="whatever" id="fieldid"> ... </form> <script type="text/javascript"> /* define function check form field value */ function containsallascii(str) { return /^[\000-\177]*$/.test(str); // returns true if ascii characters. false otherwise. } /* little jquery */ $('#fieldid').on('change', function() { str = $(this).val(); is_valid = containsallascii(str); if (!is_valid) { window.alert("there non-ascii characters in input field"); } }); </script> the above code check given field's value whenever changes (i.e. loses focus). can use .on('keyup', ... instead of .on('change', ... check field's value user typing.
finally, error message shown browser alert. crappy. can display beautiful error message, need learn little more of jquery. hope i've given starting point.
credits:
the code containsallascii function taken this answer juan mendes.
Comments
Post a Comment