前言
Django中完成表单验证,常用的有两种方法:
一种是通过HTML + JS + Ajax实现。
另一种是通过Django自身的forms模块来生成相应个HTML标签来完成表单验证。这是本节着重讲的地方
第一种方法:html + ajax实现基本的login页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .error-msg{ color: red; } </style> </head> <body> <div> <div> <input type="text" name="user" /> </div> <div> <input type="password" name="pwd" /> </div> <div> <input type="text" name="num" /> </div> <div> <input type="text" name="phone" /> </div> <input type="button" value="提交" onclick="DoSubmit();" /> </div> <script src="/static/jquery-2.1.4.min.js"></script> <script> function DoSubmit(){ var input_dict = {}; $('input').each(function(){ var v = $(this).val(); var n = $(this).attr('name'); input_dict[n] = v; }); console.log(input_dict); $('.error-msg').remove(); $.ajax({ url: '/login/', type: 'POST', data: input_dict, dataType: 'json', success: function (result) { if(result.status){ location.href = '/index/'; }else{ $.each(result.message, function (k,v) { console.log(k,v[0].message); // <span class="error-msg">错误信息</span> var tag = document.createElement('span'); tag.className = 'error-msg'; tag.innerText = v[0].message; // input[name="user"] $('input[name="' + k + '"]').after(tag); }) } }, error: function () { } }) } </script> </body> </html>