class TrackDataSchema(colander.MappingSchema): track_1 = colander.SchemaNode( colander.String(), validator=colander.Regex( r'^%?B\d{1,19}\^[A-Z /]{2,26}\^(\d|\^){4}(\d|\^){3}.*\??$', 'Track 1 does not match IATA format'), missing=colander.drop, requird=None) track_2 = colander.SchemaNode(colander.String(), validator=colander.Regex( r'^;?\d{1,19}=(\d|=){4}(\d|=){3}.*\??$', 'Track 2 does not match ABA format'), missing=colander.drop, requird=None) @staticmethod def validator(node, kw): track1 = kw.get('track_1', None) track2 = kw.get('track_2', None) if track1 is None and track2 is None: raise colander.Invalid(node, "You must provide at least one track") if track1: kw['track_1'] = str(track1).lstrip('%').rstrip('?') if track2: kw['track_2'] = str(track2).lstrip(';').rstrip('?')
class BankAccountSchema(colander.MappingSchema): account_type = colander.SchemaNode( colander.String(), validator=colander.OneOf(['checking', 'savings', 'businessChecking']), missing=colander.drop) routing_number = colander.SchemaNode(colander.String(), validator=colander.Regex( r'^[\d+]{9}$', 'The routing number is invalid'), required=True) account_number = colander.SchemaNode(colander.String(), validator=colander.Regex( r'^[\d+]{5,17}$', 'The account number is invalid'), required=True) name_on_account = colander.SchemaNode(colander.String(), validator=colander.Length(max=22), required=True) echeck_type = colander.SchemaNode( colander.String(), validator=colander.OneOf(['ARC', 'BOC', 'CCD', 'PPD', 'TEL', 'WEB']), missing=colander.drop) bank_name = colander.SchemaNode(colander.String(), validator=colander.Length(max=50), missing=colander.drop)
class CodeField(colander.SchemaNode): oid = "code" schema_type = colander.String widget = deform.widget.HiddenWidget() preparer = [prepare_ignored] validator = colander.Any(colander.Regex(r'^A\d{10}\Z'), colander.Regex(r'^IGNORED\Z', ''))
class PatchUserSchema(schemas.MappingNode): first_name = schemas.StringNode( title='First Name', missing=colander.drop, validator=colander.All( colander.Length(max=50), colander.Regex(r'^[a-zA-z0-9]+$') ), ) last_name = schemas.StringNode( title='Last Name', missing=colander.drop, validator=colander.All( colander.Length(max=50), colander.Regex(r'^[a-zA-z0-9]+$') ), ) age = schemas.UnsignedIntegerNode( title='Age', nullable=True, missing=colander.drop, ) sex = schemas.StringNode( title='Sex', missing=colander.drop, validator=colander.OneOf(['m', 'f']), nullable=True ) children = schemas.SequenceNode( Child(title='Child', missing=colander.drop), missing=colander.drop, ) current_work = Work(title='Current work', missing=colander.drop)
class HostSchema(colander.MappingSchema): dpid = colander.SchemaNode(colander.String(), missing=None) in_port = colander.SchemaNode(colander.String(), missing=None) is_gw = colander.SchemaNode(colander.String(), validator=colander.OneOf(['yes','no'])) nw_src = colander.SchemaNode(colander.String(), validator=colander.Regex(r"([0-9A-Fa-f]{1,3}[.]){3}[0-9A-Fa-f]{1,2}([/][0-9]{0,3}){0,1}")) dl_src = colander.SchemaNode(colander.String(), validator=colander.Regex(r"([0-9A-Fa-f]{1,2}[:]){5}([0-9A-Fa-f]{1,2})"))
class Passport(c.MappingSchema): byr = c.SchemaNode(c.Int(), validator=c.Range(min=1920, max=2002)) iyr = c.SchemaNode(c.Int(), validator=c.Range(min=2010, max=2020)) eyr = c.SchemaNode(c.Int(), validator=c.Range(min=2020, max=2030)) hgt = c.SchemaNode(c.String(), validator=height_validator) hcl = c.SchemaNode(c.String(), validator=c.Regex(r"^#[0-9a-f]{6}$")) ecl = c.SchemaNode(c.String(), validator=c.OneOf( ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"])) pid = c.SchemaNode(c.String(), validator=c.Regex(r"^\d{9}$"))
class CreditCardSchema(colander.MappingSchema): card_number = colander.SchemaNode(colander.String(), validator=colander.luhnok, requird=True) expiration_month = colander.SchemaNode(colander.Integer(), validator=colander.Range(1, 12), missing=None) expiration_year = colander.SchemaNode(colander.Integer(), validator=colander.Range( date.today().year, date.today().year + 7), missing=None) expiration_date = colander.SchemaNode( colander.String(), validator=colander.Regex(r'^\d{2}.?(?:\d{4}|\d{2})?$', 'The expiration date is invalid'), missing=None) card_code = colander.SchemaNode(colander.String(), validator=colander.Regex( r'^[0-9]{3,4}$', 'The card code is invalid'), missing=colander.drop) @staticmethod def validator(node, kw): exp_year = kw['expiration_year'] exp_month = kw['expiration_month'] exp_date = kw['expiration_date'] # We only need exp_date or exp_year and exp_month if exp_date is None and (exp_year is None and exp_month is None): raise colander.Invalid(node, 'You must provide a card expiration date') if exp_date is not None: exp_month = exp_date[:2] exp_year = '20' + exp_date[-2:] elif exp_month is None: raise colander.Invalid(node, 'You must provide a card expiration month') elif exp_year is None: raise colander.Invalid(node, 'You must provide a card expiration year') today = date.today() if exp_year == today.year and exp_month < today.month: raise colander.Invalid(node, 'The credit card has expired') kw['expiration_year'] = str(exp_year) kw['expiration_month'] = str(exp_month).zfill(2)
class HeaderQuotedInteger(HeaderField): """Integer between "" used in precondition headers.""" schema_type = colander.String error_message = "The value should be integer between double quotes" validator = colander.Any( colander.Regex('^"([0-9]+?)"$', msg=error_message), colander.Regex('\*')) def deserialize(self, cstruct=colander.null): param = super(HeaderQuotedInteger, self).deserialize(cstruct) if param is colander.drop or param == '*': return param return int(param[1:-1])
class POSTActivateAccountViewRequestSchema(colander.Schema): """Schema for account activation.""" path = SchemaNode(colander.String(), missing=colander.required, validator=colander.Regex('^/activate/'))
class EmailField(colander.SchemaNode): oid = "email" schema_type = colander.String widget = deform.widget.TextInputWidget() preparer = [prepare_ignored] validator = colander.Any(colander.Email(), colander.Regex(r'^IGNORED\Z', ''))
def boundingbox(self, data_input): node = colander.SchemaNode( colander.String(), name=data_input.identifier, title=data_input.title, default="0,-90,180,90", widget=deform.widget.TextInputWidget() ) # sometimes abstract is not set node.description = getattr(data_input, 'abstract', '') # optional value? if data_input.minOccurs == 0: node.missing = colander.drop # validator pattern = '-?\d+,-?\d+,-?\d+,-?\d+' regex = re.compile(pattern) node.validator = colander.Regex( regex=regex, msg='String does not match pattern: minx,miny,maxx,maxy') # finally add node to root schema # sequence of nodes ... if data_input.maxOccurs > 1: node = colander.SchemaNode( colander.Sequence(), node, name=data_input.identifier, title=data_input.title, validator=colander.Length(max=data_input.maxOccurs) ) return node
class WorkspaceSchema(colander.MappingSchema): name = colander.SchemaNode(colander.String(), title="Workspace Name", description="The name of this workspace.", validator=colander.Length(min=2)) # TODO: Put proper validation on this. stub = colander.SchemaNode( colander.String(), title="Workspace stub", description="A short, URL friendly name for the workspace.", validator=colander.Regex( VALID_IDENTIFIER, "Workspace stub must match " + VALID_IDENTIFIER.pattern)) tags = colander.SchemaNode(colander.Mapping(unknown='preserve'), title="Workspace Tags", description="A set of tags for this workspace.", missing={}, default={}) serialised_tags = colander.SchemaNode( colander.String(), title="Workspace Tags JSON", description= "JSON-encoded version of the tags for this workspace; takes precedence over tags if set", missing="", default="")
class ShortLink(colander.MappingSchema): #Todo: Reevaluate this! #The id is only used for the validation of the shorty and has to be included in the schema. The data gets #overwritten so that the id can not be fiddle with in the actual form. (Quick solution for now...) id = \ colander.SchemaNode( colander.Integer(), widget=deform.widget.HiddenWidget(), missing=u'' ) title = \ colander.SchemaNode( colander.String(), validator=colander.Length(min=3, max=75, min_err=u'Shorter than minimum length of ${min}', max_err=u'Longer than maximum length ${max}'), ) description = \ colander.SchemaNode( colander.String(), widget=deform.widget.TextAreaWidget(cols=20, rows=5), validator=colander.Length(min=3, max=512, min_err=u'Shorter than minimum length of ${min}', max_err=u'Longer than maximum length ${max}'),) url = colander.SchemaNode(colander.String(), default="http://", title=u'Url', validator=colander.Regex(expr_url, msg=u"Not valid URL")) tags = colander.SchemaNode( colander.String(), widget=deform.widget.TextInputWidget(css_class='tagit'), id='tags', missing=u'')
class CIMTransactionSchema(CIMBaseSchema, TransactionBaseSchema): recurring = colander.SchemaNode(colander.Boolean(), missing=colander.drop) card_code = colander.SchemaNode(colander.String(), validator=colander.Regex( r'^[0-9]{3,4}$', 'The card code is invalid'), missing=colander.drop)
class WikipediaSchema(colander.MappingSchema): url = colander.SchemaNode( colander.String(), validator=colander.Regex( r'(http)s?(://)(.*)(wikipedia.org/wiki/)(.*)', 'The provided URL should be for the wikipedia.org domain,' ' eg. "https://en.wikipedia.org/wiki/Dog"'))
class RegisterSchema(colander.MappingSchema): username = UserNameNode( colander.String() ).bind(request='request') password = colander.SchemaNode( colander.String(), widget=deform.widget.PasswordWidget(), validator=colander.All( colander.Length(min=8), colander.Regex('.*\d', msg='Use at least one number'), colander.Regex('.*[a-z]', msg='Use at least one lowercase char'), colander.Regex('.*[A-Z]', msg='Use at least one uppercase char'), colander.Regex('.*[^\s]', msg='Dont use whitespaces'), ) ) real_name = colander.SchemaNode(colander.String())
class HostSchema(colander.MappingSchema): nw_src = colander.SchemaNode( colander.String(), validator=colander.Regex( r"([0-9A-Fa-f]{1,3}[.]){3}[0-9A-Fa-f]{1,2}([/][0-9]{0,3}){0,1}")) dl_src = colander.SchemaNode( colander.String(), validator=colander.Regex( r"([0-9A-Fa-f]{1,2}[:]){5}([0-9A-Fa-f]{1,2})")) dpid = colander.SchemaNode(colander.String(), validator=colander.Regex(r"0x[0-9A-Fa-f]+")) in_port = colander.SchemaNode(colander.String(), validator=colander.OneOf( ["%d" % i for i in range(65536)])) is_gw = colander.SchemaNode(colander.String(), validator=colander.OneOf(['yes', 'no']))
class RegisterSchema(CSRFSchema): username = colander.SchemaNode( colander.String(), validator=colander.All( validators.Length(min=USERNAME_MIN_LENGTH, max=USERNAME_MAX_LENGTH), colander.Regex( USERNAME_PATTERN, msg=_("Must have only letters, numbers, periods, and " "underscores."), ), unique_username, unblacklisted_username, ), title=_("Username"), hint=_( "Must be between {min} and {max} characters, containing only " "letters, numbers, periods, and underscores." ).format(min=USERNAME_MIN_LENGTH, max=USERNAME_MAX_LENGTH), widget=deform.widget.TextInputWidget(autofocus=True), ) email = email_node(title=_("Email address")) password = new_password_node(title=_("Password")) privacy_accepted = colander.SchemaNode( colander.Boolean(), description=Markup(_privacy_accepted_message()), validator=privacy_acceptance_validator, widget=deform.widget.CheckboxWidget( omit_label=True, css_class="form-checkbox--inline" ), )
def test_validate_regex(self): node = colander.SchemaNode(colander.String(), validator=colander.Regex(r'foo*bar')) ret = convert(node) self.assertDictEqual(ret, { 'type': 'string', 'pattern': 'foo*bar', })
class PersonEntry(colander.MappingSchema): name = colander.SchemaNode(colander.String()) lastname = colander.SchemaNode(colander.String()) email = colander.SchemaNode(colander.String(), validator=colander.Email()) phone = colander.SchemaNode( colander.String(), validator=colander.Regex( '^\(\d{3}\) ?\d{3}( |-)?\d{4}|^\d{3}( |-)?\d{3}( |-)?\d{4}')) address = colander.SchemaNode(colander.String())
def deserialize(self, node, cstruct): if cstruct is col.null: return col.null col.Length(min=3, max=15)(node, cstruct) col.Regex(r'^[A-z][-A-z0-9]{2,}$', msg='Project shortname must begin with a letter, can ' 'contain letters, numbers, and dashes, and must be ' '3-15 characters in length.')(node, cstruct) return cstruct.lower()
class AbsolutePath(AdhocracySchemaNode): """Absolute path made with Identifier Strings. Example value: /bluaABC/_123/3 """ schema_type = colander.String relative_regex = '/[a-zA-Z0-9\_\-\.\/]+' validator = colander.Regex('^' + relative_regex + '$')
class LoginQuerystringSchema(colander.MappingSchema): """ Querystring schema for the login endpoint. """ callback = URL() scope = colander.SchemaNode(colander.String()) prompt = colander.SchemaNode(colander.String(), validator=colander.Regex("none"), missing=colander.drop)
class IsrcCodeField(colander.SchemaNode): oid = "isrc_code" schema_type = colander.String validator = colander.Regex( '^[a-zA-Z][a-zA-Z][a-zA-Z0-9][a-zA-Z0-9][a-z' 'A-Z0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*$', msg=_('Please enter a valid international ' 'standard recording code, for example: ' 'DEA123456789')) missing = ""
class ServicePlugin(Plugin): # Service definitions are identical to normal plugins, except that the # name field is required (as well as the plugin field) name = colander.SchemaNode( colander.String(), title="Service name", description="Your name for the service to identify it", validator=colander.Regex( VALID_IDENTIFIER, "Service names must match " + VALID_IDENTIFIER.pattern))
class DateSchema(colander.MappingSchema): """Payload for this queue.""" date = colander.SchemaNode(colander.Date()) timestamp = colander.SchemaNode(colander.DateTime(default_tzinfo=None)) event_name = colander.SchemaNode( colander.String(), validator=colander.Regex(r'^(([a-z])+\.([a-z])+)+$'))
class AccountRegister(colander.MappingSchema): name = colander.SchemaNode(colander.String(), validator=colander.Regex(REGISTER_NAME_RE)) fullname = colander.SchemaNode(colander.String()) email = colander.SchemaNode(colander.String(), validator=colander.Email()) password1 = colander.SchemaNode(colander.String(), validator=colander.Length(min=4)) password2 = colander.SchemaNode(colander.String(), validator=colander.Length(min=4))
def regex_validator(node, value): definition = node.metadata_definitions.get(value["name"], {}) if definition.get("type", "string") == "regex": validator = colander.Regex(definition["regex"], msg=_(definition["error_message"])) try: validator(node["string"], value["string"]) except colander.Invalid as e: error = colander.Invalid(node) error.add(e, node.children.index(node["string"])) raise error
class ProfileSchema(colander.MappingSchema): """Schema for profile edit validation""" first_name = colander.SchemaNode( colander.String(), validator=colander.Regex("^[a-zA-Z][ A-Za-z_-]*$", "First name must not contain numbers"), missing=colander.drop) last_name = colander.SchemaNode(colander.String(), validator=colander.Regex( "^[a-zA-Z][ A-Za-z_-]*$", "Last name must not contain numbers"), missing=colander.drop) nickname = Nickname_Unique(missing=colander.drop) location = colander.SchemaNode(colander.String(), validator=colander.Length(max=255), missing=colander.drop) password = colander.SchemaNode(colander.String(), validator=colander.Length(max=255), missing=colander.drop)
class ISOCountryCode(AdhocracySchemaNode): """An ISO 3166-1 alpha-2 country code (two uppercase ASCII letters). Example value: US """ schema_type = colander.String default = 'DE' missing = colander.drop validator = colander.Regex(r'^[A-Z][A-Z]$')