I am posting post data from form. I want to validate that array in controller and send a json response to the ajax call. Can you please help me with it.
This is my controller function code where I am submitting form.
public function submit()
{
$data=array(
'user_firstname'=>$_POST['user_firstname'],
'user_lastname'=>$_POST['user_lastname'],
'user_phone'=>$_POST['user_phone'],
'email'=>$_POST['user_email'],
'username'=>$_POST['user_username'],
'password'=>$_POST['user_password'],
);
$validation=validator($_POST);
if($validation->passes()){
return "Validation passes";
}
else{
return "Validation failed";
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'user_firstname' => 'required|string|max:255',
'user_lastname' => 'required|string|max:255',
'user_phone' => 'required|string|max:15|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'username' => 'required|string|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
This is my javascript function.
if(currentTab==2)
{
$.ajax({
url: "register",
type: "post",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
success: function(result){
console.log(result);
}
});
}
I want to validate the array and return all the errors in json following is my validator in the same controller.
Please suggest me if there is another way to validate data
Validation is passing every test even with empty array
$error = true; $responsecode = 400; $result["error_message"] = ""; if (sizeof($validator->errors()->getMessages()) > 0){ $messages = $validator->errors()->getMessages(); foreach ($messages as $key => $value) { $result["error_message"] .= $value[0] .' '; } }