简体   繁体   中英

what is the best way to check django form errors in javascript before submitting?

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.

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.

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