Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions itools/database/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

# Import from itools
from itools.core import is_prototype, prototype
from itools.core import is_prototype, merge_dicts, prototype
from itools.gettext import MSG
from itools.validators import validator


class Field(prototype):
Expand All @@ -27,10 +28,14 @@ class Field(prototype):
indexed = False
stored = False
multiple = False
error_messages = {
empty_values = (None, '', [], (), {})
base_error_messages = {
'invalid': MSG(u'Invalid value.'),
'required': MSG(u'This field is required.'),
}
error_messages = {}
validators = []


def get_datatype(self):
return self.datatype
Expand All @@ -41,6 +46,22 @@ def access(self, mode, resource):
return True


def get_validators(self):
validators = []
for v in self.validators:
if type(v) is str:
v = validator(v)()
validators.append(v)
return validators


def get_error_message(self, code):
messages = merge_dicts(
self.base_error_messages,
self.error_messages)
return messages.get(code)



def get_field_and_datatype(elt):
""" Now schema can be Datatype or Field.
Expand Down
29 changes: 29 additions & 0 deletions itools/validators/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: UTF-8 -*-
# Copyright (C) 2016 Sylvain Taverne <sylvain@agicia.com>
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.

# Import from itools
from base import BaseValidator
from exceptions import ValidationError
from registry import register_validator, validator
import database
import files
import password

__all__ = [
'BaseValidator',
'ValidationError',
'register_validator',
'validator']
211 changes: 211 additions & 0 deletions itools/validators/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
# -*- coding: UTF-8 -*-
# Copyright (C) 2016 Sylvain Taverne <sylvain@agicia.com>
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.

# Import from standard library
import re

# Import from itools
from itools.core import prototype, prototype_type
from itools.gettext import MSG

# Import from here
from exceptions import ValidationError
from registry import register_validator


class BaseValidatorMetaclass(prototype_type):

def __new__(mcs, name, bases, dict):
cls = prototype_type.__new__(mcs, name, bases, dict)
if 'validator_id' in dict:
register_validator(cls)
return cls


class validator_prototype(prototype):

__metaclass__ = BaseValidatorMetaclass


class BaseValidator(validator_prototype):

validator_id = None
errors = {'invalid': MSG(u'Enter a valid value')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

invalid value


def is_valid(self, value):
try:
self.check(value)
except ValidationError:
return False
return True


def check(self, value):
raise NotImplementedError('Validator is not configured')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validor must implement the check method



def get_error_msg(self):
return self.msg


def raise_default_error(self, kw={}):
code, msg = self.errors.items()[0]
raise ValidationError(msg, code, kw)


def raise_errors(self, errors, kw={}):
l = []
for code in errors:
msg = self.errors[code]
l.append((msg, code, kw))
raise ValidationError(l)


def __call__(self, value):
return self.check(value)



class EqualsValidator(BaseValidator):

validator_id = 'equals-to'
base_value = None
errors = {'not_equals': MSG(u'The value should be equals to {base_value}')}

def check(self, value):
if value != self.base_value:
kw = {'base_value': self.base_value}
self.raise_default_error(kw)



class RegexValidator(BaseValidator):

regex = None
inverse_match = False

def check(self, value):
value = str(value)
r = re.compile(self.regex, 0)
if bool(r.search(value)) != (not self.inverse_match):
self.raise_default_error()




class HexadecimalValidator(RegexValidator):

validator_id = 'hexadecimal'
regex = '^#[A-Fa-f0-9]+$'
errors = {'invalid': MSG(u'Enter a valid value.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

invalid value




class PositiveIntegerValidator(BaseValidator):

validator_id = 'integer-positive'
errors = {'integer_positive': MSG(u'Ensure this value is positive.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must be a positive integer

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C'est bizarre de définir des messages d'erreur différents à chaque fois alors que tu check juste si c'est valide ou non


def check(self, value):
if value < 0:
kw = {'value': value}
self.raise_default_error(kw)



class PositiveIntegerNotNullValidator(BaseValidator):

validator_id = 'integer-positive-not-null'
errors = {'integer_positive_not_null': MSG(u'Ensure this value is greater than 0.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must be a strictly positive integer.


def check(self, value):
if value <= 0:
kw = {'value': value}
self.raise_default_error(kw)



class MaxValueValidator(BaseValidator):

validator_id = 'max-value'
errors = {'max_value': MSG(u'Ensure this value is less than or equal to {max_value}.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must be bellow or equals to {}

max_value = None

def check(self, value):
if value and value > self.max_value:
kw = {'max_value': self.max_value}
self.raise_default_error(kw)



class MinValueValidator(BaseValidator):

validator_id = 'min-value'
errors = {'min_value': MSG(u'Ensure this value is greater than or equal to {min_value}.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must be greater than or equals to...

min_value = None

def check(self, value):
if value < self.min_value:
kw = {'min_value': self.min_value}
self.raise_default_error(kw)



class MinMaxValueValidator(BaseValidator):

validator_id = 'min-max-value'
errors = {'min_max_value': MSG(
u'Ensure this value is greater than or equal to {min_value} '

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must be between {} and {}

u'and value is less than or equal to {max_value}.')}
min_value = None
max_value = None

def check(self, value):
if value < self.min_value or value > self.max_value:
kw = {'max_value': self.max_value,
'min_value': self.min_value}
self.raise_default_error(kw)




class MinLengthValidator(BaseValidator):

validator_id = 'min-length'
min_length = 0
errors = {'min_length': MSG(u'Ensure this value has at least {min_length} characters.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must contain at least {} characters.


def check(self, value):
if len(value) < self.min_length:
kw = {'value': value,
'size': len(value),
'min_length': self.min_length}
self.raise_default_error(kw)



class MaxLengthValidator(BaseValidator):

validator_id = 'max-length'
max_length = 0
errors = {'max_length': MSG(u'Ensure this value has at most {max_length} characters.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must contains at most {} characters


def check(self, value):
if len(value) > self.max_length:
kw = {'value': value,
'size': len(value),
'max_length': self.max_length}
self.raise_default_error(kw)
47 changes: 47 additions & 0 deletions itools/validators/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: UTF-8 -*-
# Copyright (C) 2016 Sylvain Taverne <sylvain@agicia.com>
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.

# Import from itools
from itools.gettext import MSG

# Import from here
from base import BaseValidator


class UniqueValidator(BaseValidator):

validator_id = 'unique'
errors = {'unique': MSG(u'The field should be unique.')}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value must be unique

field_name = None
base_query = None

def check(self, value):
from itools.database import AndQuery, NotQuery
from itools.database import PhraseQuery
if not value:
return
context = self.context
here = context.resource
query = AndQuery(
NotQuery(PhraseQuery('abspath', str(here.abspath))),
PhraseQuery(self.field_name, value))
if self.base_query:
query.append(self.base_query)
search = context.database.search(query)
nb_results = len(search)
if nb_results > 0:
kw = {'nb_results': nb_results}
self.raise_default_error(kw)
52 changes: 52 additions & 0 deletions itools/validators/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# -*- coding: UTF-8 -*-
# Copyright (C) 2016 Sylvain Taverne <sylvain@agicia.com>
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.

# Import from itools
from itools.gettext import MSG


class ValidationError(Exception):

errors = []

def __init__(self, msg=None, code=None, msg_params=None):
errors = []
if type(msg) is list:
errors.extend(msg)
else:
errors.append((msg, code, msg_params))
self.errors = errors


def get_messages(self, field):
l = []
for msg, code, msg_params in self.errors:
field_msg = field.get_error_message(code) if field else None
msg = field_msg or msg
l.append(msg.gettext(**msg_params))
return l


def get_message(self, field=None, mode='html'):
messages = self.get_messages(field)
if mode == 'html':
msg = '<br/>'.join(messages)
return MSG(msg, format='html')
return '\n'.join(messages)


def __str__(self):
return self.get_message()
Loading