This repository has been archived on 2024-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
old-scribeengine/scribeengine/lib/validation/client.py
2010-01-15 22:55:30 +02:00

231 lines
8.6 KiB
Python

# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
###############################################################################
# ScribeEngine - Open Source Blog Software #
# --------------------------------------------------------------------------- #
# Copyright (c) 2010 Raoul Snyman #
# --------------------------------------------------------------------------- #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as published by the Free #
# Software Foundation; version 2 of the License. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
"""
Client-side validators.
"""
import logging
log = logging.getLogger(__name__)
class JSValidator(object):
"""
This is a class used to create a validation rule in javascript.
"""
def __init__(self, *args, **kwargs):
"""
The constructor is used to create the validator.
field
The name of the field.
required
Whether or not this field is required.
type
The type of field. Can be "string", "number", "email", "integer"
"""
if u'type' not in kwargs:
raise KeyError(u'"type" is a required argument.')
self.validators = {}
for key, arg in kwargs.iteritems():
self.validators[key] = arg
def to_javascript(self):
js_validators = []
for key, value in self.validators.iteritems():
if key == u'message':
continue
elif key == u'type':
if value in ['email', 'number', 'url']:
key = value
value = u'true'
else:
continue
#elif key == u'checked':
# key = 'required'
# if value:
# value = u'checked'
# else:
# value = u'unchecked'
elif key == u'condition':
conditions = value.split(u',')
values = []
for condition in conditions:
subconditions = condition.split(u';')
subvalues = []
for subcondition in subconditions:
if subcondition.find(u'==') >= 0:
parts = subcondition.split(u'==')
subvalues.append(u'$("%s").val() == %s' % (parts[0], parts[1]))
elif subcondition.find(u'>=') >= 0:
parts = subcondition.split(u'>=')
subvalues.append(u'$("%s").val() >= %s' % (parts[0], parts[1]))
elif subcondition.find(u'<=') >= 0:
parts = subcondition.split(u'<=')
subvalues.append(u'$("%s").val() <= %s' % (parts[0], parts[1]))
elif subcondition.find(u'>') >= 0:
parts = subcondition.split(u'>')
subvalues.append(u'$("%s").val() > %s' % (parts[0], parts[1]))
elif subcondition.find(u'<') >= 0:
parts = subcondition.split(u'<')
subvalues.append(u'$("%s").val() < %s' % (parts[0], parts[1]))
elif subcondition.find(u'!=') >= 0:
parts = subcondition.split(u'!=')
subvalues.append(u'$("%s").val() != %s' % (parts[0], parts[1]))
#elif subcondition.find(u'@') >= 0:
# parts = subcondition.split(u':')
# subvalues.append(u'$("%s").attr(%s)' % (parts[0], parts[1]))
elif subcondition.find(u':') >= 0:
parts = subcondition.split(u':')
subvalues.append(u'$("%s").is(":%s")' % (parts[0], parts[1]))
else:
subvalues.append(u'$("%s")' % subcondition)
values.append(u' && '.join(subvalues))
value = u'function () { return (%s); }' % u') || ('.join(values)
key = u'required'
elif isinstance(value, bool):
if value:
value = u'true'
else:
value = u'false'
elif isinstance(value, basestring):
if isinstance(value, str):
value = unicode(value, u'utf-8')
value = u'"%s"' % value
else:
value = unicode(value)
js_validators.append(u'%s: %s' % (key, value))
return u', '.join(js_validators)
def get_message(self):
"""
If a message is set for this validator, return it, else return None.
"""
if 'message' in self.validators:
return self.validators['message']
else:
return None
class JSNumber(JSValidator):
"""
This is a specialised version of JSValidator for numbers.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'number'
if 'condition' not in kwargs:
kwargs['required'] = True
JSValidator.__init__(self, *args, **kwargs)
class JSDigits(JSValidator):
"""
This is a specialised version of JSValidator for digits.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'digits'
JSValidator.__init__(self, *args, **kwargs)
class JSString(JSValidator):
"""
This is a specialised version of JSValidator for strings.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'string'
JSValidator.__init__(self, *args, **kwargs)
class JSName(JSValidator):
"""
This is a specialised version of JSValidator for names.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'string'
kwargs['realname'] = True
JSValidator.__init__(self, *args, **kwargs)
class JSAlphanumeric(JSValidator):
"""
This is a specialised version of JSValidator for alphanumeric strings.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'string'
kwargs['alphanumeric'] = True
JSValidator.__init__(self, *args, **kwargs)
class JSEmail(JSValidator):
"""
This is a specialised version of JSValidator for strings.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'email'
JSValidator.__init__(self, *args, **kwargs)
class JSUrl(JSValidator):
"""
This is a specialised version of JSValidator for strings.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'url'
JSValidator.__init__(self, *args, **kwargs)
class JSDate(JSValidator):
"""
This is a specialised version of JSValidator for dates.
"""
def __init__(self, *args, **kwargs):
kwargs['type'] = u'date'
JSValidator.__init__(self, *args, **kwargs)
class JSDropdown(JSValidator):
"""
This is a copy of the DropdownValidator for Formencode.
"""
def __init__(self, *args, **kwargs):
if 'invalid_option' not in kwargs:
invalid_option = 0
else:
invalid_option = kwargs['invalid_option']
del kwargs['invalid_option']
if 'condition' not in kwargs:
kwargs['required'] = True
kwargs['notvalue'] = invalid_option
kwargs['type'] = u'string'
JSValidator.__init__(self, *args, **kwargs)
class JSCheckbox(JSValidator):
"""
A validator for maching sure checkboxes are checked.
"""
def __init__(self, *args, **kwargs):
if 'checked' not in kwargs:
kwargs['checked'] = True
kwargs['type'] = u'string'
JSValidator.__init__(self, *args, **kwargs)