DataValidator Class Documentation
DataValidator is a fluent PHP class (namespace: Nobanno) for validating and sanitizing data from user input, supporting a wide range of rules and types. All validation failures throw a Nobanno\ValidationException.
Namespace: Nobanno
Exception: Nobanno\ValidationException
1. Basic Usage
use Nobanno\DataValidator;
use Nobanno\ValidationException;
try {
$value = (new DataValidator())
->title('Customer Name')
->post('customer_name')
->required()
->asAlphabetic(true)
->minLen(3)
->maxLen(50)
->sanitize()
->validate();
// Use $value
} catch (ValidationException $e) {
echo $e->getMessage();
}
2. Setting the Value
- value($val): Set value manually
- post($field): Get value from
$_POST
- get($field): Get value from
$_GET
- default($val): Set a default value if input is empty
3. Label/Title
- label($str): (deprecated) Set label for error messages
- title($str): Set human-readable name for error messages
4. Sanitization
- sanitize(): Remove tags, slashes, and convert HTML special chars
- removeTags($allowableTags = null)
- removeSlash()
- convert($convertDoubleQuote, $convertSingleQuote)
5. Required/Optional
- required(): Mark as required (throws if empty)
- optional(): Mark as optional (default)
6. Language Checks
- englishOnly(): Only English letters, numbers, spaces
- banglaOnly(): Only Bengali characters and spaces
7. Type Checks
- asAlphabetic($allowSpace): Only A-Z/a-z (optionally spaces)
- asNumeric(): Only numbers
- asAlphaNumeric($allowSpace): Only A-Z/a-z/0-9 (optionally spaces)
- asString($allowSpace): Any string (optionally spaces)
- asInteger($allowNegative): Integer (optionally negative)
- asFloat($allowNegative): Float (optionally negative)
- asArray(): Must be array
- asEmail(): Valid email
- asMobile(): Valid Bangladeshi mobile, returns 8801... format
- asDate($timezone = 'Asia/Dhaka'): Valid date (d-m-Y)
- asBool(): Boolean
8. Length & Range
- exactLen($len): Exact length
- minLen($len): Minimum length
- maxLen($len): Maximum length
- minVal($min): Minimum value
- maxVal($max): Maximum value
9. Miscellaneous
- startsWith($str): Must start with string
- endsWith($str): Must end with string
10. Finalizing
- validate(): Returns the validated value or default, throws on failure
11. Example: Validating a POST Email
try {
$email = (new DataValidator())
->title('Email')
->post('email')
->required()
->asEmail()
->sanitize()
->validate();
} catch (ValidationException $e) {
echo $e->getMessage();
}
12. Exception Handling
All validation failures throw ValidationException with a descriptive message. Use try/catch to handle errors.
13. Tips & Best Practices
- Chain methods for readable validation logic.
- Always call
validate() at the end.
- Use
default() for optional fields.
- Use
sanitize() to clean user input before saving or displaying.
14. References