3

Actually I need a method which have same error message in javascript validation (client side) and in my django form validation (server side).

I search for any django library for this but I didn't find any. This is the most relative question I founded in SO, but it seems not helpful:

Django Javascript form validation

Do you know any django library for this or if not what is the best method to do this?

Thanks in advance.

5
  • why do you want javascript to do that when the form does a good job fr you ? You can use the jquery's validation plugin to achieve though Commented May 29, 2013 at 15:38
  • It's more convenient for user (because check after submitting is costly). Commented May 29, 2013 at 15:39
  • Basically, you can use a jquery plugin like : jqueryvalidation.org, and before submit, validate the form fields Commented May 29, 2013 at 15:46
  • Why not just use HTML5 validation? Its quite good, that way, you barely have to even deal with erroneous input. Commented May 29, 2013 at 18:17
  • HTML5 validation (with the 'pattern' attribute) doesn't work with textarea unfortunately... Commented Oct 3, 2017 at 14:34

1 Answer 1

1

I couldn't find any existing library to do this easily, so I use a workaround.

Django form errors are in list format. Its difficult to transfer a list of dict from Django to JS. I have a function that comes in handy. This function (convertErrorsToDict) concatenates all errors per parameter together into 1 error.:

views.py:

def convertErrorsToDict(errors): #previously errors={f1:[er1]}. make it {f1:'er1'} so we can render nicely
    #converts form errors from list to dictionary
    errors2={}
    for f in errors:
        errors2[f]='.'.join(errors[f])
    return (errors2)


def setPassword(request):
    your_form=FormName();
    context={}
    errors=convertErrorsToDict(your_form.errors)
    context['errors']=errors;
    return render(request,'htmlFileName.html',context)

FileName.html:

{% load jsonify %}
<script type="text/javascript">
    var errors={{errors|jsonify}};    
</script>

FileName.js In js file we can now directly use errors as a variable.

console.log(errors.para1) //para1 is first para in the form. eg first_name
console.log(errors.para2) 

This feature is useful when we need complete control on form errors content.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.