Пример #1
0
 def validate_same_value(data):
     if data.test_invariant_field1 != data.test_invariant_field2:
         raise Invalid(u"Must have same values")
Пример #2
0
def future_date(value):
    if value and not value >= datetime.datetime.today():
        raise Invalid(_(u"Time limit date can not be before today."))
    return True
Пример #3
0
def validate_service_indicators_order(order):
    if not is_valid_service_indicators_order(order):
        raise Invalid(_(u"El format ha de ser 3.1, 1.2, 1.3"))
    return True
Пример #4
0
 def check_passwords_match(schema):
     """Password and confirmation must match"""
     if schema.password != schema.confirmation:
         raise Invalid(_(u"Your password and confirmation did not match. "
                         u"Please try again."))
Пример #5
0
 def validate(self, value):
     super(EmailAddressValidator, self).validate(value)
     if not value or not is_email_valid(value):
         raise Invalid(_(u'This email address is invalid.'))
Пример #6
0
 def validate_link(data):
     if data.link and len(data.link) != 1:
         raise Invalid("Must select 1 link only")
Пример #7
0
 def validate_same_value(data):
     if data.new_password != data.new_password_confirmation:
         raise Invalid(
             _("Password doesn't compare with confirmation value"))
Пример #8
0
 def validate_location_required(data):
     if data.meeting_type != 'webinar' and data.location is None:
         raise Invalid(
             _(u"Event location input is missing." +
               " This field is not required only in " +
               "'Meeting type: webinar' case."))
Пример #9
0
def validateemail(value):
    if not checkemail(value):
        raise Invalid(_(safe_unicode('Invalid email address')))
    return True
Пример #10
0
def validateEmail(value):
    if not checkEmail(value):
        raise Invalid(_(safe_unicode("Invalid email address")))
    return True
Пример #11
0
 def validate(self, value):
     if not value:
         raise Invalid(
             _(u'error_not_accepted',
               default=u'You need to accept the terms and conditions'))
     return
Пример #12
0
def validateImageextension(value):
    if not checkfileextensionimage(value.filename):
        raise Invalid(safe_unicode(
            "You could only add images in the png, gif or jpg file format "
            "to your project."))
    return True
Пример #13
0
def isNotEmptyCategory(value):
    if not value:
        raise Invalid(
            safe_unicode(
                'You have to choose at least one category for your project.'))
    return True
Пример #14
0
 def title_or_file_required(data):
     if not data.title and not data.file:
         raise Invalid(
             _(u'error_title_or_file_required',
               default=u'Either the title or the file is '
               'required.'))
Пример #15
0
 def validateReferenceOrLink(data):
     if not data.content and not data.link:
         raise Invalid(
             _(u"You must enter either a content item or "
               u"an external link"))
Пример #16
0
    def handleApply(self, action):
        data = self.extractData()[0]
        given_username = data.get("user", "").strip()
        given_message = data.get("message", "") or ""
        given_message = given_message.strip()
        workspace_title = safe_unicode(self.context.title)
        if not given_username:
            return

        ws = IWorkspace(self.context)
        for name in ws.members:
            member = api.user.get(username=name)
            if member is not None:
                if member.getUserName() == given_username:
                    raise WidgetActionExecutionError(
                        'user',
                        Invalid("User is already a member of this workspace"))

        user = api.user.get(username=given_username)
        email = user.getProperty("email")

        token_util = getUtility(ITokenUtility)
        token_id, token_url = token_util.generate_new_token(
            redirect_path="resolveuid/%s" % (ws.context.UID(), ))
        storage = get_storage()
        storage[token_id] = (ws.context.UID(), given_username)

        current_user = api.user.get_current()
        inviter = current_user.getProperty("fullname", None)
        if not inviter:
            inviter = current_user.getUserName()
        inviter = safe_unicode(inviter)

        msg_header = u"You have been invited to join %s by %s" % (
            workspace_title, inviter)

        if given_message:
            optional = "Here is the message from %s\n\n" % inviter
            optional = "%s%s\n\n" % (optional, given_message)
            given_message = optional

        msg_footer = u"""
The following is a unique URL tied to your email address ({email}).

Following the link will make you a member of the {workspace} workspace
automatically.

{token_url}

""".format(email=email, workspace=workspace_title, token_url=token_url)

        message = u"{header}\n\n{optional}{footer}".format(
            header=msg_header,
            optional=given_message,
            footer=msg_footer,
        )

        subject = u'You are invited to join "%s"' % workspace_title

        send_email(email, subject, message)
        api.portal.show_message(
            'Invitation sent to %s' % email,
            self.request,
        )
Пример #17
0
 def validate(self, value):
     super(TestValidator, self).validate(value)
     raise Invalid("Test")
    def handleSaveImport(self, action):
        """Create and handle form button "Save and Import"."""

        # Extract form field values and errors from HTTP request
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return False

        import_file = data["import_file"]


        if not import_file:
            raise WidgetActionExecutionError('import_file',
                Invalid(_(u"Please provide a csv file to import")))
            return


        # File upload is not saved in settings
        file_resource = import_file.data
        file_name = import_file.filename

        if not (import_file.contentType.startswith("text/") or \
            import_file.contentType.startswith("application/csv")):
            raise WidgetActionExecutionError('import_file',
                Invalid(_(u"Please provide a file of type CSV")))
            return
        if import_file.contentType.startswith("application/vnd.ms-excel"):
            raise WidgetActionExecutionError('import_file',
                Invalid(_(u"Please convert your Excel file to CSV first")))
            return



        if data["object_type"] in ['__ignore__', '__stop__']:
            create_new = False
            object_type = None
        else:
            create_new = True
            object_type = data["object_type"]

        # list all the dexterity types
        #dx_types = get_portal_types(self.request)
        #log.debug(dx_types)

        # based from the types, display all the fields
        # fields = get_schema_info(CREATION_TYPE)
        # log.debug(fields)

        # blank header or field means we don't want it
        header_mapping = [d for d in data['header_mapping'] if d['field'] and d['header']]

        matching_headers = dict([(d['field'],d['header']) for d in header_mapping])


        if create_new and not(matching_headers.get('id') or matching_headers.get('title')):
            raise WidgetActionExecutionError('header_mapping',
                Invalid(_(u"If creating new content you need either 'Short Name"
                u" or 'Title' in your data.")))
            return

        if not matching_headers:
            raise WidgetActionExecutionError('header_mapping',
                Invalid(_(u"You must pick which fields should contain your data")))
            return

        primary_key = data["primary_key"]
        if primary_key and not matching_headers.get(primary_key):
            raise WidgetActionExecutionError('primary_key',
                Invalid(_(u"Must be a field selected in Header Mapping")))
            return

        # based from the matching fields, get all the values.
        matching_fields = dict([(d['header'],d['field']) for d in header_mapping])
        import_metadata = dexterity_import(
            self.context,
            file_resource,
            matching_fields,
            object_type,
            create_new,
            primary_key
        )

        existing_count = import_metadata["existing_count"]
        new_count = import_metadata["new_count"]
        ignore_count = import_metadata["ignore_count"]

        api.portal.show_message(
            message=_("import_message_csv_info",  # nopep8
                default=u"""${new_num} items added,
                    ${existing_num} items updated and
                    ${ignore_num} items skipped
                    from ${filename}""",
                mapping={"new_num": new_count,
                    "existing_num": existing_count,
                    "ignore_num": ignore_count,
                    "filename": file_name}),
            request=self.request,
            type="info")

        self.import_metadata = import_metadata

        # Save our sucessful settings to save time next import
        annotations = IAnnotations(self.context)
        settings = annotations.setdefault(KEY, {})
        settings['header_list'] = [d['header'] for d in header_mapping]
        # we will keep making this bigger in case they switch between several CSVs
        settings.setdefault("matching_fields",{}).update(matching_fields)
        settings['primary_key'] = primary_key
        settings['object_type'] = object_type

        return True
Пример #19
0
def is_email(value):
    if not re.match('^' + EMAIL_RE, value) or not FULL_DOMAIN_RE.match(value):
        raise Invalid(u'Please enter a valid e-mail address.')
    return True
Пример #20
0
 def validate_isFull(data):
     if data.modality == 'Empresa' and not data.company:
         raise Invalid(_(u"Falta omplir les dades d'empresa"))
     if not data.lang:
         raise Invalid(_(u'Falta omplir "Idioma del treball"'))
Пример #21
0
def checkFieldName(val):
    for letter in val:
        if letter not in _valid_field_name_chars:
            raise Invalid('Not a valid field name')
    return True
Пример #22
0
 def validate(self, value):
     if ActorLookup(value).is_team() and not self.context.is_open():
         raise Invalid(
             _(u'error_no_team_responsible_in_progress_state',
               default=u'Team responsibles are only allowed if the task or '
               u'forwarding is open.'))
Пример #23
0
 def reminder_option_date_validator(data):
     if data.reminder_option == ReminderOnDate.option_type and \
             not data.reminder_option_date:
         raise Invalid(
             _(u'no_remind_date_error',
               default=u'Please choose a remind date'))
Пример #24
0
 def licensenotchoosen(value):
     if not value.licenses_choice:
         raise Invalid(_(safe_unicode(
             "Please choose a license for your release.")))
Пример #25
0
def rating_constraint(value):
    if value <= 0 or value > 5:
        raise Invalid(_(u'Please enter 1 to 5 in the Rating field'))
    return True
Пример #26
0
 def compatibilitynotchoosen(data):
     if not data.compatibility_choice:
         raise Invalid(_(safe_unicode(
             "Please choose one or more compatible product versions for "
             "your release")))
Пример #27
0
 def price_invariant(data):
     if data.price < data.salePrice:
         raise Invalid(_(u'The sale price is bigger than price!'))
     if data.price < data.disc_amount:
         raise Invalid(_(u'The Discount Amount is bigger than price!'))
Пример #28
0
 def noOSChosen(data):
     if data.link_to_file is not None and data.platform_choice == []:
         raise Invalid(
             _(safe_unicode(
                 "Please choose a compatible platform "
                 "for the linked file.")))
Пример #29
0
def checkEmail(value):
    try:
        checkEmailAddress(value)
    except EmailAddressInvalid:
        raise Invalid(_(u"Invalid email address."))
    return True
Пример #30
0
 def validateAction(self, data):
     # TODO: check data ...
     # ...
     datasets = data.get('projection', {})
     if not tuple(chain.from_iterable(x for x in datasets.values())):
         raise ActionExecutionError(Invalid('No projection dataset selected.'))