# Validation

# Basics

Sh Framework Validates almost same way normal laravel validation works. Failed validation response returns with http status 422.

Below is a basic example of how to validate a post request from a post api request, check keenly on error returned on failed validation and also on success

$data = \request()->all();
$valid = Validator::make($data,[
    'name' => 'required',
    'description' => 'required|max:255',
]);
if (count($valid->errors())) {
//return error response with status code 422
    return response([
        'status' => 'failed',
        'errors' => $valid->errors()
    ], 422);
}
$task = Task::create([
    'name'=>request('name'),
    'description'=>request('description')
]);

//return a successful response
return [
    'status'=>'success',
    'task'=>$task
];

# Custom Validation

At times you may want to return a custom validation error message not in laravel validator

A good scenario for custom validation is when a user wants to change their email address in the system, you first check if that email has already been taken if it has, return a email exists validation error.

$email = request('email'); 
$exists = User::where('email','like',$email)->count();
if($exists !== 0) {
    return response([
        'status' => 'failed',
        'errors' => ['email'=>['Email has been taken already']]
    ], 422);
}
// proceed with creating user etc