[Answered ]-Invalid RegEx Entered by User in Django Form Causes 500 Server Error

1👍

Wrap the make_concordance in tryexcept; if an exception occurs,
render the original form template for the user, along with the error information.

import re
try:
    context, texts_len, results_len = make_concordance(searchterm, search_type)
except re.error as e:
    form._errors['search_term'] = str(e)
    del form.cleaned_data['search_term']

    return render_to_response('corpus/search_test.html', 
         {'form': form}, context_instance=RequestContext(request))

The better way could be to make a custom cleaner, but it seems to be a bit more complicated, and I do not have Django.

1👍

I ended up building a custom cleaner, as Antti mentioned. This is what worked in the end:

def clean(self):
    cleaned_data = self.cleaned_data
    searchterm = cleaned_data.get('searchterm')
    search_type = cleaned_data.get('search_type')
    if search_type == 'regex':
        try:
            re.search(searchterm, 'randomdatastring') #this is just to test if the regex is valid
        except re.error:
            raise forms.ValidationError("Invalid regular expression.")
    return cleaned_data

0👍

To build on @Sam’s comment, here’s how to capture the specific error when a regular expression fails to compile:

import re
err_message = None
try:
    re.compile('(unbalanced')
except re.error as exc:
    err_message = 'Uhoh: {}'.format(exc)

print err_message

Output:

Uhoh: unbalanced parenthesis

Leave a comment