def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        key_values = list(value.keys())
        key_schema = list(o['key'] for o in self.checklist)
        unused_keys = copy(key_schema)

        for k in key_values:
            if k not in key_schema:
                raise FieldError((
                    "Answer Key '{0}' is not a valid"
                    " option for this form.").format(k))
            else:
                unused_keys.remove(k)
                if not isinstance(value[k], bool):
                    raise FieldError((
                        "'{0}': Expected boolean, got '{1}'").format(
                            k, type(value[k]).__name__ 
                        ))

        if len(unused_keys) > 0:
            raise FieldError((
                    "The following keys are missing from the answer:"
                    "{0}").format(unused_keys))

        for validator in self.validation_classes:
            validator.validate(value)
Example #2
0
 def check_widget(self, widget):
     if not isinstance(widget, dict):
         raise FieldError(
             "Invalid 'widget' definition, expected 'dictionary', got '{0}'"
             .format(type(widget).__name__))
     try:
         if widget['type'] not in self.allowed_widgets:
             raise FieldError(
                 ("Field '{0}' of type '{1}' does not accept the '{2}' "
                  "widget type").format(self.id, self.type, widget['type']))
     except KeyError:
         raise FieldError("Invalid 'widget' definition")
Example #3
0
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        if 'option' in value and value['option'] not in self.option_values:
            raise FieldError(
                "'{0}' is not a a correct option value".format(value))
        if ('option' in value and value['option'] == 'OTHER'
                and not value['answer']):
            raise FieldError({
                'id': 'section1.errors.other_option',
            })

        for validator in self.validation_classes:
            validator.validate(value)
Example #4
0
 def validate_value(self, value):
     # Check if the value for this field's answer is valid.
     if value not in self.option_values:
         raise FieldError(
             "'{0}' is not a a correct option value".format(value))
     for validator in self.validation_classes:
         validator.validate(value)
 def validate(self, field):
     if self.value not in field:
         raise FieldError({
             'id': 'section1.errors.contains',
             'values': {
                 'word': self.value
             }
         })
Example #6
0
    def validate_schema(cls, field):
        errors = []
        expected_keys = list(cls.EXPECTED_KEYS)
        optional_keys = list(cls.OPTIONAL_KEYS)
        for key in field:
            if key in expected_keys:
                expected_keys.remove(key)
            else:
                try:
                    optional_keys.remove(key)
                except ValueError:
                    errors.append(
                        "Key '{0}' either doesn't belong in the field schema "
                        "or is duplicated".format(key))

        for key in expected_keys:
            errors.append(
                "Required key '{0}' is missing from the field schema".format(
                    key))

        if errors:
            raise FieldError(errors)

        if not isinstance(field['values'], list):
            errors.append("'values' property must be a list")
            raise FieldError(errors)

        for value in field['values']:
            if not isinstance(value, dict):
                errors.append(
                    "Every element of 'values' property must be a dictionary")
                continue
            expected_values_keys = ['key', 'value']
            for key in value:
                if key in expected_values_keys:
                    expected_values_keys.remove(key)
                else:
                    errors.append("Key '{0}' doesn't belong in field values "
                                  "schema".format(key))

            for key in expected_values_keys:
                errors.append("Required key '{0}' missing in field values "
                              "schema".format(key))

        if errors:
            raise FieldError(errors)
Example #7
0
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        try:
            self.decimals
        except AttributeError:
            self.decimals = False

        invalid_values = []
        sum = 0
        for option in value.keys():
            str_option_values = [str(x) for x in self.option_values]
            if option not in str_option_values:
                invalid_values.append(
                    "'{0}' is not a a correct option value".format(option))
            if value[option]:
                try:
                    float_value = float(value[option])
                except ValueError:
                    invalid_values.append(
                        "Answer for option '{0}' must be a number".format(
                            option))
                    continue
                if not self.decimals and not float_value.is_integer():
                    invalid_values.append({
                        'id': 'section1.errors.rank_field.only_integer',
                        'values': {
                            'option': option
                        }
                    })

                sum += float_value

        if invalid_values:
            raise FieldError(invalid_values)

        if sum != self.sum_total:
            raise FieldError({
                'id': 'section1.errors.rank_field.add',
                'values': {
                    'total': self.sum_total
                }
            })

        for validator in self.validation_classes:
            validator.validate(value)
Example #8
0
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        try:
            float(value)
        except ValueError:
            raise FieldError("'{0}' is not a number".format(value))

        for validator in self.validation_classes:
            validator.validate(value)
 def validate(self, field):
     if len(field) < int(self.value):
         raise FieldError({
             'id': 'section1.errors.min_length',
             'values': {
                 'min': self.value,
                 'answer': len(field)
             }
         })
 def validate(self, field):
     if int(field) > int(self.value):
         raise FieldError({
             'id': 'section1.errors.max_value',
             'values': {
                 'max': self.value,
                 'answer': int(field)
             }
         })
    def validate_schema(cls, field):

        allowed_types = list(cls.ALLOWED_SHAPE_TYPES)
        if field['shape'] not in allowed_types:
            raise FieldError(
                "Type '{0}' is not a valid shape option."
                " Must be one of: "
                "'Polygon', 'Point' or 'LineString'".format(field['shape']))

        super().validate_schema(field)
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        if isinstance(value, dict):
            try:
                GEOSGeometry(json.dumps(value))
            except GEOSException:
                raise FieldError("geoJSON geometry is not valid")

            except (ValueError, TypeError, GDALException):
                raise FieldError("malformed geoJSON")

            if self.shape != value['type']:
                raise FieldError(
                    "geoJSON must be of type '{0}'".format(self.shape)
                )
        else:
            raise FieldError("value must be an object")

        for validator in self.validation_classes:
            validator.validate(value)
Example #13
0
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        if not re.match(self.EMAIL_RE, value):
            raise FieldError({
                'id': 'section1.errors.invalid_email',
                'values': {
                    'answer': value
                }
            })

        for validator in self.validation_classes:
            validator.validate(value)
Example #14
0
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        invalid_values = []
        for v in value:
            if v not in self.option_values:
                invalid_values.append(
                    "'{0}' is not a a correct option value".format(v))
        if invalid_values:
            raise FieldError(invalid_values)

        for validator in self.validation_classes:
            validator.validate(value)
 def validate(self, field):
     for _, value in field.items():
         if isinstance(value, dict):
             # In case field type is Rank Other
             value = value['value']
         if value is not None and int(value) > int(self.value):
             raise FieldError({
                 'id': 'section1.errors.rank_field.max_value',
                 'values': {
                     'max': self.value,
                     'answer': int(value)
                 }
             })
Example #16
0
    def validate_value(self, value):
        # Check if the value for this field's answer is valid.
        try:
            float_value = float(value)
        except ValueError:
            raise FieldError("'{0}' is not a number".format(value))

        try:
            self.decimals
        except AttributeError:
            self.decimals = False

        if not self.decimals and not float_value.is_integer():
            raise FieldError({
                'id': 'section1.errors.only_integer',
                'values': {
                    'answer': value
                }
            })

        for validator in self.validation_classes:
            validator.validate(value)
Example #17
0
 def check_validators(self, validators, **kwargs):
     errors = []
     for validator in validators:
         try:
             validator_class = ValidatorFactory.get_class(validator['type'])
         except KeyError:
             errors.append("Invalid validator type: '{0}'".format(
                 validator['type']))
             continue
         try:
             validator_obj = validator_class(validator, self)
             self.validation_classes.append(validator_obj)
         except ValidationError as e:
             errors = []
             for err in e:
                 errors.append(str(err))
             raise FieldError(errors)
Example #18
0
    def validate_schema(cls, field):
        errors = []
        expected_keys = list(cls.EXPECTED_KEYS)
        optional_keys = list(cls.OPTIONAL_KEYS)
        for key in field:
            if key in expected_keys:
                expected_keys.remove(key)
            else:
                try:
                    optional_keys.remove(key)
                except ValueError:
                    errors.append(
                        "Key '{0}' either doesn't belong in the field schema "
                        "or is duplicated".format(key))

        for key in expected_keys:
            errors.append(
                "Required key '{0}' is missing from the field schema".format(
                    key))

        if errors:
            raise FieldError(errors)
Example #19
0
 def validate_value(self, value):
     # Check if the value for this field's answer is valid.
     if not isinstance(value, bool):
         raise FieldError("Expected boolean value, got '{0}'".format(
             type(value).__name__))
Example #20
0
    def check_answers(self, answers):
        if not isinstance(answers, dict):
            raise FormatError(
                "Expected answers to be a 'dictionary', got {0} instead"
                .format(type(answers).__name__))
                
        answer_keys = answers.keys()
        invalid_keys = []
        for key in answer_keys:
            try:
                self.fields[key.__str__()]
            except KeyError:
                invalid_keys.append(
                    "Field '{0}' does not match any field on the form."
                    .format(key))
                continue
        if invalid_keys:
            raise FieldError(invalid_keys)

        errors = []
        error = {
            'id': '',
            'message': {}
        }
        # We check for answers for each of the form's fields
        for key in self.fields:
            field = self.fields[key.__str__()]
            is_hidden, is_required = self.check_state(key, answers)
            try:
                answer = answers[key]
            except KeyError:
                if is_required and not is_hidden:
                    error['id'] = key
                    error['message'] = {
                        "id": "section1.errors.required_field"
                    }
                    errors.append(copy(error))
                continue
            # If the field is hidden we don't need the answer
            if is_hidden:
                del answers[key]
                continue
            # If there is no answer for a field we don't run validations
            if answer is None or answer == "":
                if is_required and not is_hidden:
                    error['id'] = key
                    error['message'] = {
                        "id": "section1.errors.required_field"
                    }
                    errors.append(copy(error))
            else:
                try:
                    field.validate_value(answer)
                except FieldError as err:
                    error['id'] = key
                    for e in err:
                        error['message'] = e
                        errors.append(copy(error))
        if errors:
            result = {
                'result': 'ANSWER_ERROR',
                'errors': errors
            }
            return result
        else:
            success = {}
            success['result'] = "OK"
            success['message'] = "The answer is valid."
            return success