validation-py


Namevalidation-py JSON
Version 0.2.0 PyPI version JSON
download
home_pagehttps://github.com/jedymatt/validation-py
SummaryValidation
upload_time2023-10-30 08:50:22
maintainer
docs_urlNone
authorJedy Matt Tabasco
requires_python
licenseMIT
keywords validation validator flask
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # validation-py

Inspired from Laravel's validation

Features:
- Custom rules
-  flask support


## Getting Started


```sh
pip intall validation-py
```


## Basic Usage

```py
data = {'name': 'John Doe', 'age': 18}
```

```py
from validator.rules import Rules


validator = Validator(data, rules={
        "name": [Rules.REQUIRED, Rules.STRING],
        "age": [Rules.REQUIRED, Rules.INTEGER, AgeRule],
    })

if validator.fails():
    errors = validator.errors() # error messages

validated = validator.validated() # validated data

```

```py
from validator.rules import Rules


validated = Validator(data, rules={
        "name": [Rules.REQUIRED, Rules.STRING],
        "age": [Rules.REQUIRED, Rules.INTEGER, AgeRule],
    }).validate() # immediately raise ValidationError when fails 

```


## Custom Rules

As function

```py
def validate_age(field, value, fail):
    if value is None or isinstance(value, str):
            return

    if value < 18:
        fail(f"The {field} must be 18 or above")

```

As class

```py
from validation.validation_rule import ValidationRule


class AgeRule(ValidationRule):
    def passes(self, field, value):
        self._field = field

        if value is None or isinstance(value, str):
            return

        return value >= 18

    def message(self):
        return f"The {self._field} must be 18 or above"
```


## How to use with Flask

Go to `example/flask_app` for more info

```py
# ...
from validation import Rules
from flask_validation import (
    FlaskValidation,
    convert_empty_to_none,
    transform_to_primitive_types,
)
from validation.validation_rule import ValidationRule


app = Flask(__name__)
validation = FlaskValidation(app)

# set a secret key for session
app.secret_key = "secret" 

@app.route("/", methods=["GET", "POST"])
def home():
    if request.method == "POST":
        validated = validation.validate(
            rules={
                "name": [Rules.required, Rules.string, [Rules.min, 3]],
                "age": [Rules.required, Rules.integer, AgeRule], # AgeRule is a custom Rule class
            },
            before_validation=[
                lambda data: transform_to_primitive_types(["age"], data, int),
                convert_empty_to_none,
            ],
        )

        session['validated'] = validated

        return redirect("/sucess")

    return render_template("home.html")
```

To know how to access error messages, and old field values, check out `example/flask_app/templates/home.html`
```py
# to get all errors
error()
# to get value by key, defaults to "" empty string
error('name')


# get all old values, see the `example/flask_app/templates/home.html` on its uses
# same as above
old()
old('name')
```

To protect sensitive fields, you can add `exclude_from_session` decorator on your route method
```py
from validation.flask_validation


app = Flask(__name__)
validation = FlaskValidation(app)


@app.route('/home')
@validation.exclude_from_session("password", "token", "..")
def home():
    """perform validation here"""
```

## How to Contribute?

Since this package is new, you can contribute by adding validation for email, float, array, password, and so on. To make it rest API friendly, make the validation error, returned as json, customizable.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/jedymatt/validation-py",
    "name": "validation-py",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "validation,validator,flask",
    "author": "Jedy Matt Tabasco",
    "author_email": "jedymatt@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/be/75/bab7a62433920cd46cba9b7764b9d1cd9fc1369969ba665f1a345ffcc007/validation-py-0.2.0.tar.gz",
    "platform": null,
    "description": "# validation-py\n\nInspired from Laravel's validation\n\nFeatures:\n- Custom rules\n-  flask support\n\n\n## Getting Started\n\n\n```sh\npip intall validation-py\n```\n\n\n## Basic Usage\n\n```py\ndata = {'name': 'John Doe', 'age': 18}\n```\n\n```py\nfrom validator.rules import Rules\n\n\nvalidator = Validator(data, rules={\n        \"name\": [Rules.REQUIRED, Rules.STRING],\n        \"age\": [Rules.REQUIRED, Rules.INTEGER, AgeRule],\n    })\n\nif validator.fails():\n    errors = validator.errors() # error messages\n\nvalidated = validator.validated() # validated data\n\n```\n\n```py\nfrom validator.rules import Rules\n\n\nvalidated = Validator(data, rules={\n        \"name\": [Rules.REQUIRED, Rules.STRING],\n        \"age\": [Rules.REQUIRED, Rules.INTEGER, AgeRule],\n    }).validate() # immediately raise ValidationError when fails \n\n```\n\n\n## Custom Rules\n\nAs function\n\n```py\ndef validate_age(field, value, fail):\n    if value is None or isinstance(value, str):\n            return\n\n    if value < 18:\n        fail(f\"The {field} must be 18 or above\")\n\n```\n\nAs class\n\n```py\nfrom validation.validation_rule import ValidationRule\n\n\nclass AgeRule(ValidationRule):\n    def passes(self, field, value):\n        self._field = field\n\n        if value is None or isinstance(value, str):\n            return\n\n        return value >= 18\n\n    def message(self):\n        return f\"The {self._field} must be 18 or above\"\n```\n\n\n## How to use with Flask\n\nGo to `example/flask_app` for more info\n\n```py\n# ...\nfrom validation import Rules\nfrom flask_validation import (\n    FlaskValidation,\n    convert_empty_to_none,\n    transform_to_primitive_types,\n)\nfrom validation.validation_rule import ValidationRule\n\n\napp = Flask(__name__)\nvalidation = FlaskValidation(app)\n\n# set a secret key for session\napp.secret_key = \"secret\" \n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n    if request.method == \"POST\":\n        validated = validation.validate(\n            rules={\n                \"name\": [Rules.required, Rules.string, [Rules.min, 3]],\n                \"age\": [Rules.required, Rules.integer, AgeRule], # AgeRule is a custom Rule class\n            },\n            before_validation=[\n                lambda data: transform_to_primitive_types([\"age\"], data, int),\n                convert_empty_to_none,\n            ],\n        )\n\n        session['validated'] = validated\n\n        return redirect(\"/sucess\")\n\n    return render_template(\"home.html\")\n```\n\nTo know how to access error messages, and old field values, check out `example/flask_app/templates/home.html`\n```py\n# to get all errors\nerror()\n# to get value by key, defaults to \"\" empty string\nerror('name')\n\n\n# get all old values, see the `example/flask_app/templates/home.html` on its uses\n# same as above\nold()\nold('name')\n```\n\nTo protect sensitive fields, you can add `exclude_from_session` decorator on your route method\n```py\nfrom validation.flask_validation\n\n\napp = Flask(__name__)\nvalidation = FlaskValidation(app)\n\n\n@app.route('/home')\n@validation.exclude_from_session(\"password\", \"token\", \"..\")\ndef home():\n    \"\"\"perform validation here\"\"\"\n```\n\n## How to Contribute?\n\nSince this package is new, you can contribute by adding validation for email, float, array, password, and so on. To make it rest API friendly, make the validation error, returned as json, customizable.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Validation",
    "version": "0.2.0",
    "project_urls": {
        "Homepage": "https://github.com/jedymatt/validation-py",
        "Source": "https://github.com/jedymatt/validation-py",
        "Tracker": "https://github.com/jedymatt/validation-py/issues"
    },
    "split_keywords": [
        "validation",
        "validator",
        "flask"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b011ec87f77f66461d80d5f16846f1971cfe90e0b817d4e136e21e0fdbc225e4",
                "md5": "09d8b40173cbfeb80bcf567f04d5af9d",
                "sha256": "7d10cbc1e6e39499089cf64991a39246e8311ab219946881b22175f634857308"
            },
            "downloads": -1,
            "filename": "validation_py-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "09d8b40173cbfeb80bcf567f04d5af9d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 8692,
            "upload_time": "2023-10-30T08:50:21",
            "upload_time_iso_8601": "2023-10-30T08:50:21.534023Z",
            "url": "https://files.pythonhosted.org/packages/b0/11/ec87f77f66461d80d5f16846f1971cfe90e0b817d4e136e21e0fdbc225e4/validation_py-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "be75bab7a62433920cd46cba9b7764b9d1cd9fc1369969ba665f1a345ffcc007",
                "md5": "01b156c3f551b4a8f594eb1f0a43ab4a",
                "sha256": "259c4d5d422c3b4112f6fb30f069ed9a576c75cc38dafc5d97748d7348408f07"
            },
            "downloads": -1,
            "filename": "validation-py-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "01b156c3f551b4a8f594eb1f0a43ab4a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 7805,
            "upload_time": "2023-10-30T08:50:22",
            "upload_time_iso_8601": "2023-10-30T08:50:22.967068Z",
            "url": "https://files.pythonhosted.org/packages/be/75/bab7a62433920cd46cba9b7764b9d1cd9fc1369969ba665f1a345ffcc007/validation-py-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-30 08:50:22",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "jedymatt",
    "github_project": "validation-py",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "validation-py"
}
        
Elapsed time: 0.17247s