简体   繁体   中英

Warn on non-ASCII Characters in Django Form

I'm trying to add some client-side Ajax validation of my Django form. I want to warn users, as they are typing in a field, if any of the characters they just inputted are not ascii.

I originally put the basic python to check for ascii characters in my form's clean method. I don't want to do that, though, as I don't want to produce an error but rather just give a warning message and let the user continue with the rest of the form.

try:
    field_value.decode('ascii')
except UnicodeEncodeError:
    #raise forms.ValidationError("Non-ASCII characters may cause issues in registering your data. Consider removing these characters. You may still submit at your own risk.")
    # Just want to show a warning so the user can still submit the form if they wish

I want to show a small warning under the field as the user is typing. I've tried using django-dajax, but am not sure. How can I do this?

EDIT: To clarify, I want to show the warning before the user submits the form. So, as they are filling out the form...

Use

> <input type="text" pattern="^[\x20-\x7F]+$" id ....>

in html

Use JavaScript to validate that form field.

Example (using jQuery):

<form>
    <input name="whatever" id="fieldId">
    ...
</form>

<script type="text/javascript">

    /* Define a function to check the form field value */

    function containsAllAscii(str) {
        return  /^[\000-\177]*$/.test(str); // returns true if all are ASCII characters. false otherwise. 
    }

    /* Now a little jQuery */

    $('#fieldId').on('change', function() {
        str = $(this).val();
        is_valid = containsAllAscii(str);

        if (!is_valid) {
            window.alert("There are Non-ASCII characters in the input field");
        }
    });   
</script>

The above code will check the given field's value whenever it changes ( ie loses focus). You can use .on('keyup', ... instead of .on('change', ... which will check the field's value as the user is typing.

Finally, the error message that is shown is just a browser alert. Which is crappy. You can display a beautiful error message, you just need to learn a little more of jQuery. But I hope I've given you a good starting point.


Credits:

The code for containsAllAscii function is taken from this answer by Juan Mendes .

In your django form, create a custom field and take advantage of the media class.

from django import forms

class MyWidget(forms.TextInput):
    class Media:
        css = {
            'all': ('pretty.css',)
        }
        js = ('animations.js', 'actions.js')

and set the js to the javascript file you will use for validation. something along the lines of the the other answer

https://docs.djangoproject.com/en/1.9/topics/forms/media/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM