我正在尝试添加一些我的Django表单的客户端Ajax验证。我想警告用户,因为他们正在输入字段,如果他们输入的任何字符不是ascii。
我最初使用基本的python来检查我的表单clean
方法中的ascii字符。我不想这样做,因为我不想产生错误,而只是发出警告信息,让用户继续使用表格的其余部分。
try:
field_value.decode('ascii')
except UnicodeEncodeError:
#raise forms.ValidationError("Non-ASCII characters may cause issues in registering your data. Consider removing these characters. You may still submit at your own risk.")
# Just want to show a warning so the user can still submit the form if they wish
我想在用户输入时在字段下显示一个小警告。我尝试过使用django-dajax,但我不确定。我怎么能这样做?
编辑: 为了澄清,我想在用户提交表单之前显示警告。所以,因为他们填写表格......
答案 0 :(得分:0)
使用JavaScript验证表单字段。
示例(使用jQuery):
<form>
<input name="whatever" id="fieldId">
...
</form>
<script type="text/javascript">
/* Define a function to check the form field value */
function containsAllAscii(str) {
return /^[\000-\177]*$/.test(str); // returns true if all are ASCII characters. false otherwise.
}
/* Now a little jQuery */
$('#fieldId').on('change', function() {
str = $(this).val();
is_valid = containsAllAscii(str);
if (!is_valid) {
window.alert("There are Non-ASCII characters in the input field");
}
});
</script>
上述代码会在更改时检查给定字段的值(即失去焦点)。您可以使用.on('keyup', ...
代替.on('change', ...
,这会在用户输入时检查字段的值。
最后,显示的错误消息只是浏览器警报。这很糟糕。您可以显示一个漂亮的错误消息,您只需要学习更多jQuery。但我希望我能给你一个很好的起点。
现金:
containsAllAscii
功能的代码来自this answer Juan Mendes。
答案 1 :(得分:0)
在您的django表单中,创建一个自定义字段并利用媒体类。
from django import forms
class MyWidget(forms.TextInput):
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')
并将js设置为您将用于验证的javascript文件。与其他答案一致的东西
答案 2 :(得分:0)
使用
> <input type="text" pattern="^[\x20-\x7F]+$" id ....>
以html