{
    "mode": "info",
    "parameter": "Data::FormValidator::Constraints",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/info/Data%3A%3AFormValidator%3A%3AConstraints/json",
    "generated": "2026-07-05T09:23:37Z",
    "synopsis": "use Data::FormValidator::Constraints qw(:closures);\nIn an Data::FormValidator profile:\nconstraintmethods => {\nemail   => email(),\nphone   => americanphone(),\nfirstnames =>  {\nconstraintmethod => FVmaxlength(3),\nname => 'mycustomname',\n},\n},\nmsgs => {\nconstraints => {\nmycustomname => 'My message',\n},\n},",
    "sections": {
        "Data::FormValidator::CUserrContributed PeData::FormValidator::Constraints(3pm)": {
            "content": "",
            "subsections": []
        },
        "NAME": {
            "content": "Data::FormValidator::Constraints - Basic sets of constraints on input\nprofile.\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Data::FormValidator::Constraints qw(:closures);\n\nIn an Data::FormValidator profile:\n\nconstraintmethods => {\nemail   => email(),\nphone   => americanphone(),\nfirstnames =>  {\nconstraintmethod => FVmaxlength(3),\nname => 'mycustomname',\n},\n},\nmsgs => {\nconstraints => {\nmycustomname => 'My message',\n},\n},\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "These are the builtin constraints that can be specified by name in the\ninput profiles.\n\nBe sure to check out the SEE ALSO section for even more pre-packaged\nconstraints you can use.\n\nFVlengthbetween(1,23)\nFVmaxlength(23)\nFVminlength(1)\nuse Data::FormValidator::Constraints qw(\nFVlengthbetween\nFVminlength\nFVmaxlength\n);\n\nconstraintmethods => {\n\n# specify a min and max, inclusive\nlastname        => FVlengthbetween(1,23),\n\n}\n\nSpecify a length constraint for a field.\n\nThese constraints have a different naming convention because they are\nhigher-order functions. They take input and return a code reference to\na standard constraint method. A constraint name of \"lengthbetween\",\n\"minlength\", or \"maxlength\" will be set, corresponding to the\nfunction name you choose.\n\nThe checks are all inclusive, so a max length of '100' will allow the\nlength 100.\n\nLength is measured in perl characters as opposed to bytes or anything\nelse.\n\nThis constraint will untaint your data if you have untainting turned\non. However, a length check alone may not be enough to insure the\nsafety of the data you are receiving.  Using additional constraints to\ncheck the data is encouraged.\n\nFVeqwith\nuse Data::FormValidator::Constraints qw( FVeqwith );\n\nconstraintmethods => {\npassword  => FVeqwith('passwordconfirm'),\n}\n\nCompares the current field to another field.  A constraint name of\n\"eqwith\" will be set.\n\nFVnumvalues\nuse Data::FormValidator::Constraints qw ( FVnumvalues );\n\nconstraintmethods => {\nattachments => FVnumvalues(4),\n}\n\nChecks the number of values in the array named by this param.  Note\nthat this is useful for making sure that only one value was passed for\na given param (by supplying a size argument of 1).  A constraint name\nof \"numvalues\" will be set.\n\nFVnumvaluesbetween\nuse Data::FormValidator::Constraints qw ( FVnumvaluesbetween );\n\nconstraintmethods => {\nattachments => FVnumvaluesbetween(1,4),\n}\n\nChecks that the number of values in the array named by this param is\nbetween the supplied bounds (inclusively).  A constraint name of\n\"numvaluesbetween\" will be set.\n\nemail\nChecks if the email LOOKS LIKE an email address. This should be\nsufficient 99% of the time.\n\nLook elsewhere if you want something super fancy that matches every\npossible variation that is valid in the RFC, or runs out and checks\nsome MX records.\n\nstateorprovince\nThis one checks if the input correspond to an american state or a\ncanadian province.\n\nstate\nThis one checks if the input is a valid two letter abbreviation of an\nAmerican state.\n\nprovince\nThis checks if the input is a two letter Canadian province\nabbreviation.\n\nziporpostcode\nThis constraints checks if the input is an American zipcode or a\nCanadian postal code.\n\npostcode\nThis constraints checks if the input is a valid Canadian postal code.\n\nzip\nThis input validator checks if the input is a valid american zipcode :\n5 digits followed by an optional mailbox number.\n\nphone\nThis one checks if the input looks like a phone number, (if it contains\nat least 6 digits.)\n\namericanphone\nThis constraints checks if the number is a possible North American\nstyle of phone number : (XXX) XXX-XXXX. It has to contains 7 or more\ndigits.\n\nccnumber\nThis constraint references the value of a credit card type field.\n\nconstraintmethods => {\nccno      => ccnumber({fields => ['cctype']}),\n}\n\nThe number is checked only for plausibility, it checks if the number\ncould be valid for a type of card by checking the checksum and looking\nat the number of digits and the number of digits of the number.\n\nThis functions is only good at catching typos. IT DOESN'T CHECK IF\nTHERE IS AN ACCOUNT ASSOCIATED WITH THE NUMBER.\n\nccexp\nThis one checks if the input is in the format MM/YY or MM/YYYY and if\nthe MM part is a valid month (1-12) and if that date is not in the\npast.\n\ncctype\nThis one checks if the input field starts by M(asterCard), V(isa),\nA(merican express) or D(iscovery).\n\nipaddress\nThis checks if the input is formatted like a dotted decimal IP address\n(v4).  For other kinds of IP address method, See Regexp::Common::net\nwhich provides several more options. \"REGEXP::COMMON SUPPORT\" explains\nhow we easily integrate with Regexp::Common.\n",
            "subsections": []
        },
        "RENAMING BUILT-IN CONSTAINTS": {
            "content": "If you'd like, you can rename any of the built-in constraints. Just\ndefine the constraintmethod and name in a hashref, like this:\n\nconstraintmethods => {\nfirstnames =>  {\nconstraintmethod => FVmaxlength(3),\nname => 'customlength',\n}\n},\n\nREGEXP::COMMON SUPPORT\nData::FormValidator also includes built-in support for using any of\nregular expressions in Regexp::Common as named constraints. Simply use\nthe name of regular expression you want.  This works whether you want\nto untaint the data or not. For example:\n\nuse Data::FormValidator::Constraints qw(:regexpcommon);\n\nconstraintmethods => {\nmyipaddress => FVnetIPv4(),\n\n# An example with parameters\notherip      => FVnetIPv4(-sep=>' '),\n}\n\nNotice that the routines are named with the prefix \"FV\" instead of\n\"RE\" now.  This is simply a visual cue that these are slightly\nmodified versions. We've made a wrapper for each Regexp::Common routine\nso that it can be used as a named constraint like this.\n\nBe sure to check out the Regexp::Common syntax for how its syntax\nworks. It will make more sense to add future regular expressions to\nRegexp::Common rather than to Data::FormValidator.\n",
            "subsections": []
        },
        "PROCEDURAL INTERFACE": {
            "content": "You may also call these functions directly through the procedural\ninterface by either importing them directly or importing the whole\n:validators group.  This is useful if you want to use the built-in\nvalidators out of the usual profile specification interface.\n\nFor example, if you want to access the email validator directly, you\ncould either do:\n\nuse Data::FormValidator::Constraints (qw/validemail/);\nor\nuse Data::FormValidator::Constraints (:validators);\n\nif (validemail($email)) {\n# do something with the email address\n}\n\nNotice that when you call validators directly, you'll need to prefix\nthe validator name with \"valid\"\n\nEach validator also has a version that returns the untainted value if\nthe validation succeeded. You may call these functions directly through\nthe procedural interface by either importing them directly or importing\nthe :matchers group. For example if you want to untaint a value with\nthe email validator directly you may:\n\nif ($email = matchemail($email)) {\nsystem(\"echo $email\");\n}\nelse {\ndie \"Unable to validate email\";\n}\n\nNotice that when you call validators directly and want them to return\nan untainted value, you'll need to prefix the validator name with\n\"match\"\n",
            "subsections": []
        },
        "WRITING YOUR OWN CONSTRAINT ROUTINES": {
            "content": "New School Constraints Overview\nThis is the current recommended way to write constraints. See also \"Old\nSchool Constraints\".\n\nThe most flexible way to create constraints to use closures-- a normal\nseeming outer subroutine which returns a customized DFV method\nsubroutine as a result.  It's easy to do. These \"constraint methods\"\ncan be named whatever you like, and imported normally into the name\nspace where the profile is located.\n\nLet's look at an example.\n\n# Near your profile\n# Of course, you don't have to export/import if your constraints are in the same\n# package as the profile.\nuse My::Constraints 'coolness';\n\n# In your profile\nconstraintmethods => {\nemail            => email(),\nprospectivedate => coolness( 40, 60,\n{fields => [qw/personality smarts goodlooks/]}\n),\n}\n\nLet's look at how this complex \"coolness\" constraint method works. The\ninterface asks for users to define minimum and maximum coolness values,\nas well as declaring three data field names that we should peek into to\nlook their values.\n\nHere's what the code might look like:\n\nsub coolness {\nmy ($mincool,$maxcool, $attrs) = @;\nmy ($personality,$smarts,$looks) = @{ $attrs->{fields} } if $attrs->{fields};\nreturn sub {\nmy $dfv = shift;\n\n# Name it to refer to in the 'msgs' system.\n$dfv->namethis('coolness');\n\n# value of 'prospectivedate' parameter\nmy $val = $dfv->getcurrentconstraintvalue();\n\n# get other data to refer to\nmy $data = $dfv->getfiltereddata;\n\nmy $hasallthree = ($data->{$personality} && $data->{$smarts} && $data->{$looks});\nreturn ( ($val >= $mincool) && ($val <= $maxcool) && $hasallthree );\n}\n}\n\nOld School Constraints\nHere is documentation on how old school constraints are created. These\nare supported, but the new school style documented above is\nrecommended.\n\nSee also the \"validatorpackages\" option in the input profile, for\nloading sets of old school constraints from other packages.\n\nOld school constraint routines are named two ways. Some are named with\nthe prefix \"match\" while others start with \"valid\". The difference is\nthat the \"match\" routines are built to untaint the data and return a\nsafe version of it if it validates, while \"valid\" routines simply\nreturn a true value if the validation succeeds and false otherwise.\n\nIt is preferable to write \"match\" routines that untaint data for the\nextra security benefits. Plus, Data::FormValidator will AUTOLOAD a\n\"valid\" version if anyone tries to use it, so you only need to write\none routine to cover both cases.\n\nUsually constraint routines only need one input, the value being\nspecified.  However, sometimes more than one value is needed.\n\nExample:\n\nimagefield  => {\nconstraintmethod  => 'maximagedimensions',\nparams => [\\100,\\200],\n},\n\nUsing that syntax, the first parameter that will be passed to the\nroutine is the Data::FormValidator object. The remaining parameters\nwill come from the \"params\" array. Strings will be replaced by the\nvalues of fields with the same names, and references will be passed\ndirectly.\n\nIn addition to \"constraintmethod\", there is also an even older\ntechnique using the name \"constraint\" instead. Routines that are\ndesigned to work with \"constraint\" don't have access to\nData::FormValidator object, which means users need to pass in the name\nof the field being validated. Besides adding unnecessary syntax to the\nuser interface, it won't work in conjunction with\n\"constraintregexpmap\".\n\nMethods available for use inside of constraints\nA few useful methods to use on the Data::FormValidator::Results object\nare available to you to use inside of your routine.\n\ngetinputdata()\n\nReturns the raw input data. This may be a CGI object if that's what was\nused in the constraint routine.\n\nExamples:\n\n# Raw and uncensored\nmy $data = $self->getinputdata;\n\n# tamed to be a hashref, if it wasn't already\nmy $data = $self->getinputdata( ashashref => 1 );\n\ngetfiltereddata()\n\nmy $data = $self->getfiltereddata;\n\nReturns the valid filtered data as a hashref, regardless of whether it\nstarted out as a CGI.pm compatible object. Multiple values are\nexpressed as array references.\n\ngetcurrentconstraintfield()\n\nReturns the name of the current field being tested in the constraint.\n\nExample:\n\nmy $field = $self->getcurrentconstraintfield;\n\nThis reduces the number of parameters that need to be passed into the\nroutine and allows multi-valued constraints to be used with\n\"constraintregexpmap\".\n\nFor complete examples of multi-valued constraints, see\nData::FormValidator::Constraints::Upload\n\ngetcurrentconstraintvalue()\n\nReturns the name of the current value being tested in the constraint.\n\nExample:\n\nmy $value = $self->getcurrentconstraintvalue;\n\nThis reduces the number of parameters that need to be passed into the\nroutine and allows multi-valued constraints to be used with\n\"constraintregexpmap\".\n\ngetcurrentconstraintname()\n\nReturns the name of the current constraint being applied\n\nExample:\n\nmy $value = $self->getcurrentconstraintname;\n\nThis is useful for building a constraint on the fly based on its name.\nIt's used internally as part of the interface to the Regexp::Commmon\nregular expressions.\n\nuntaintedconstraintvalue()\n\nreturn $dfv->untaintedconstraintvalue($match);\n\nIf you have written a constraint which untaints, use this method to\nreturn the untainted result. It will prepare the right result whether\nthe user has requested untainting or not.\n\nnamethis()\n\nsetcurrentconstraintname()\n\nSets the name of the current constraint being applied.\n\nExample:\n\nsub myconstraint {\nmy @outerparams = @;\nreturn sub {\nmy $dfv = shift;\n$dfv->setcurrentconstraintname('myconstraint');\nmy @params = @outerparams;\n# do something constraining here...\n}\n}\n\nBy returning a closure which uses this method,  you can build an\nadvanced named constraint in your profile, before you actually have\naccess to the DFV object that will be used later. See\nData::FormValidator::Constraints::Upload for an example.\n\n\"namethis\" is a provided as a shorter synonym.\n\nThe \"meta()\" method may also be useful to communicate meta data that\nmay have been found. See Data::FormValidator::Results for documentation\nof that method.\n",
            "subsections": []
        },
        "BACKWARDS COMPATIBILITY": {
            "content": "Prior to Data::FormValidator 4.00, constraints were specified a bit\ndifferently.  This older style is still supported.\n\nIt was not necessary to explicitly load some constraints into your name\nspace, and the names were given as strings, like this:\n\nconstraints  => {\nemail         => 'email',\nfax           => 'americanphone',\nphone         => 'americanphone',\nstate         => 'state',\nmyipaddress => 'REnetIPv4',\notherip => {\nconstraint => 'REnetIPv4',\nparams => [ \\'-sep'=> \\' ' ],\n},\nmyccno      => {\nconstraint => 'ccnumber',\nparams => [qw/ccno cctype/],\n}\n},\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Constraints available in other modules\nData::FormValidator::Constraints::Upload - validate the bytes, format\nand dimensions of file uploads\nData::FormValidator::Constraints::DateTime - A newer DateTime\nconstraint module. May save you a step of transforming the date into a\nmore useful format after it's validated.\nData::FormValidator::Constraints::Dates - the original DFV date\nconstraint module. Try the newer one first!\nData::FormValidator::Constraints::Japanese - Japan-specific constraints\nData::FormValidator::Constraints::MethodsFactory - a useful collection\nof tools generate more complex constraints. Recommended!\n\nRelated modules in this package\nData::FormValidator::Filters - transform data before constraints are\napplied\nData::FormValidator::ConstraintsFactory - This is a historical\ncollection of constraints that suffer from cumbersome names. They are\nworth reviewing though-- \"makeandconstraint\" will allow one to\nvalidate against a list of constraints and shortcircuit if the first\none fails. That's perfect if the second constraint depends on the first\none having passed. For a modern version of this toolkit, see\nData::FormValidator::Constraints::MethodsFactory.\nData::FormValidator\n",
            "subsections": []
        },
        "CREDITS": {
            "content": "Some of those input validation functions have been taken from MiniVend\nby Michael J. Heins\n\nThe credit card checksum validation was taken from contribution by\nBruce Albrecht to the MiniVend program.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Francis J. Lacoste\nMichael J. Heins\nBruce Albrecht\nMark Stosberg\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c) 1999 iNsu Innovations Inc.  All rights reserved.\n\nParts Copyright 1996-1999 by Michael J. Heins Parts Copyright 1996-1999\nby Bruce Albrecht Parts Copyright 2005-2009 by Mark Stosberg\n\nThis program is free software; you can redistribute it and/or modify it\nunder the terms as perl itself.\n\nperl v5.26.1                      2017-10Data::FormValidator::Constraints(3pm)",
            "subsections": []
        }
    },
    "summary": "Data::FormValidator::Constraints - Basic sets of constraints on input profile.",
    "flags": [],
    "examples": [],
    "see_also": []
}