Skip to content

Instantly share code, notes, and snippets.

@mki
Created August 23, 2012 09:04
Show Gist options
  • Select an option

  • Save mki/3434463 to your computer and use it in GitHub Desktop.

Select an option

Save mki/3434463 to your computer and use it in GitHub Desktop.
Собственная проверка поля формы в Django (see more at http://mkifiles.ru/?p=1758)
# -*- coding: utf-8 -*-
from django import forms
from django.core.validators import email_re
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
# Наше поле для валидации
class ContactField(forms.Field):
def validate(self, value):
super(ContactField, self).validate(value)
# Проверяем на соответствие поля "email"у
if email_re.search(smart_unicode(value)):
pass
# Проверяем на соответствие поля телефонному номеру
elif re.compile("^([0-9\(\)\/\+ \-]*)$").search(smart_unicode(value)):
pass
# Если не соответствует ничему, то вызываем ошибку
else:
raise forms.ValidationError(_(u'Enter a valid email or phone number.'), code='invalid')
class MessagesForm(forms.Form):
contact = ContactField(required=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment