<?php /** * Violin example. Errors for a specific field. * * Simply getting a list of errors for a specific field that * occured while trying to validate the data passed in * against the rules given. */ require '../../vendor/autoload.php'; use Violin\Violin; $v = new Violin(); $v->validate(['username' => ['dalegarrett1234567890', 'required|alpha|min(3)|max(20)'], 'email' => ['dale.codecourse.com', 'required|email']]); var_dump($v->errors()->get('username')); // Array of all 'username' errors.
<?php /** * Violin example. Checking and getting first error. * * This checks a specific field has an error, and then outputs * the first error that occured for that field. This is most * likely what you'd use in a real life situation within * your HTML form. */ require '../../vendor/autoload.php'; use Violin\Violin; $v = new Violin(); $v->validate(['username' => ['dalegarrett1234567890', 'required|alpha|min(3)|max(20)'], 'email' => ['dale.codecourse.com', 'required|email']]); if ($v->errors()->has('email')) { // Check if any errors exist for 'email'. echo $v->errors()->first('email'); // First 'email' error (string). }
<?php /** * Violin example. Basic validation, two arrays. * * This shows basic validation using two arrays, one for data, * and one for the ruleset. This is useful if you'd like to * extract the rules to a seperate class or variable. */ require '../vendor/autoload.php'; use Violin\Violin; $v = new Violin(); $data = ['username' => 'dale', 'email' => '*****@*****.**', 'password' => 'ilovecats', 'password_confirm' => 'ilovecats']; $rules = ['username' => 'required|alpha|min(3)|max(20)', 'email' => 'required|email', 'password' => 'required', 'password_confirm' => 'required|matches(password)']; $v->validate($data, $rules); if ($v->passes()) { // Passed } else { var_dump($v->errors()->all()); }
if (!$auth->isLoggedIn()) { header("Location: index.php"); die; } if (!empty($_POST)) { // keep track validation errors $usernameError = null; $passwordError = null; $valid = true; // keep track post values $username = $_POST['username']; $password = $_POST['password']; $v = new Violin(); $v->validate(['username' => [$username, 'required|alpha|min(3)|max(20)'], 'password' => [$password, 'required|alpha|min(3)']]); if (!$v->passes()) { $usernameError = $v->errors()->get('username')[0]; $passwordError = $v->errors()->get('password')[0]; $valid = false; } $options = ["cost" => 12]; $hashedPassword = password_hash($password, PASSWORD_BCRYPT, $options); // insert data if ($valid) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO user (username, password) values(?, ?)"; $query = $pdo->prepare($sql); $query->execute(array($username, $hashedPassword)); Database::disconnect(); header("Location: index.php"); }