Javascript driven forms in Django -


django uses forms api input validation. form sent template, , rendered html (as_p , friends).

when user ready, post form, data validated, , form re-rendered on template if not valid.

this odd when form not valid because lack of enough caracteres (i.e. min_length) on field or invalid characters: 1 post tell user missing basic.

so, there available way (django or app) of rendering form javascript code "tests"[*] of form' fields on client-side? i.e. have form rendered as_javascript(...) dynamically shows error messages shown form.errors?

this should not work fields because require database hit, should work on simple (and common) fields, namely charfield, textfield, etc.

[*] "tests" because validation has made on server-side.

so want validate in js before submitting. here's 1 way that. instead of putting input of type submit in form should put button of type button:

<form id="my-form" submit="...">   ...           <input type='button' id='submit-button' value="save"> </form> 

note unless specify type "button", still try submit.

then in js file write (include jquery in html file):

$('#submit-button').click(function() {   var errors = testerrors(); // function tests errors.   if (errors != "") {     alert(errors);   } else {     $('#my-form').submit();   } } 

example testerrors():

function testerrors() {     var country         = $("#id_country").val();     var city            = $("#id_city").val();      var errors = "";     if (country == "") {         errors += "- please select country\n";     }     if (city.length <= 10 ) {         errors += "- city name short\n";     }     return errors; } 

so in testerrors define own tests each field. in example there two, country , city. country code tests whether it's blank , city whether it's longer 10 characters. can define further tests of own. please refer jquery documentation on how retrieve values different types of form fields.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -