jquery validation engine ajax验证,在django中应用jQuery-Validation-Engine的ajax方式验证用户名...

蒲坚
2023-12-01

jQuery-Validation-Engine是一个相当不错的表单验证插件,用ajaxUserCall可以实现不刷新验证用户名的

功能,但它的例子中,服务器端是用java和php来验证的,那如何用在django中呢,下面我来说下,用这个

方法也可以验证email的唯一性,随你的应用了。

在url中定义:

url(r'^ajaxvalidateusername/$', ajaxvalidateusername, name='userena_ajaxvalidateusername'),

在views.py中:

def ajaxvalidateusername(request):

fieldId = request.GET.get('fieldId')

username = request.GET.get('fieldValue')

try:

user = User.objects.get(username__iexact=username)

except User.DoesNotExist:

info = _('This username is validate.')

is_validate = True

else:

info = _('This username is already taken.')

is_validate = False

result = [fieldId, is_validate, info]

json = simplejson.dumps(result)

return HttpResponse(json)

在forms.py中:

username_attrs_dict = {'class': 'validate[required,custom[cjusername],ajax[ajaxUserCall]] '}

USERNAME_RE = r'^[a-zA-Z]{1}([\.\w]+)$'

class yourForm(forms.Form):

username = forms.RegexField(regex=USERNAME_RE,

max_length=30,

widget=forms.TextInput(attrs=username_attrs_dict),

label=_("Username"),

error_messages={'invalid': _('Username must be started with letters, and contain only letters, numbers, dots and underscores.')})

在模板中:

{{ form.username }}

在jquery.validationEngine-zh_CN.js添加和修改以下内容

"cjusername": {

"regex": /^[a-zA-Z]{1}([\.\w]+)$/,

"alertText": "* 必须以字母开始,至少两个字符"

},

// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings

"ajaxUserCall": {

"url": "/ajaxvalidateusername/",

// you may want to pass extra data on the ajax call

"extraData": "",

"alertText": "* 此名称已被其他人使用",

"alertTextLoad": "* 正在确认名称是否有其他人使用,请稍等。"

},

搞定!

阅读(3208) | 评论(0) | 转发(0) |

 类似资料: