How can i validate this string with the laravel validation? I want to check if the dates between the commas is a date.
2017-11-11,2017-12-11-2017,2017-13-11
In reply to your comment. Yes laravel can do that, by creating a request class like this.
<?php namespace App\Laravel\Requests\Backoffice;
use Session,Auth, Input;
use App\Laravel\Requests\RequestManager;
class DateRequest extends RequestManager{
public function rules(){
$rules = [
//validate if the value is a date and check the date_format must be in "Y-d-m" form
'date' => 'date|date_format:"Y-d-m"',
];
return $rules;
}
public function messages(){
return [
'date' => "Invalid date.",
'date_format' => "Invalid date format.",
];
}
}
You can use explode() array function, It split a string and convert it to array.
$date_string = '2017-11-11,2017-12-11-2017,2017-13-11';
//Split the $date_string
$dates = explode(',',$date_string);
//get the values of the $dates variable
foreach($dates as $date){
//Check if the $date values are valid or not
if(Carbon::createFromFormat('DATE FORMAT',$date) !== false){
//valid date format
}else{
//invalid date format
}
}
You can do it with using Rule Objects more elegant, next time you can reuse this validation/rule.
Run php artisan make:rule Stringdate
app/Rules/Stringdate.php file will be generated.
change passes method like this
public function passes($attribute, $value)
{
if(!$value){
return false;
}
$dates = explode(',',$value);
foreach ($dates as $date){
if(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date) < 1){
return false;
}
}
return true;
}
The validation you can make in controller, for ex.
$this->validate(request(),['data' => ['required',new Stringdate()]]);
(data is your attribute name)
in that case you should create a custom validator for the comma delimiter date string so can still use the Request class.
public function validateSampleCustom($attribute, $value, $parameters){
...do you custom code here
...where value is the passed value from the input field
...parameters are the value after the semi_colon in your request eg : (sample_custom:param1,param2,...,paramn)
}
i can show you some custom validator
public function validateOldPassword($attribute, $value, $parameters){
if($parameters){
$user_id = $parameters[0];
$user = User::find($user_id);
return Hash::check($value,$user->password);
}
return FALSE;
}
I just want to clarify your concern so we can help you with your issues. and i use this to my Request class by calling it this way
'password' => "required|old_password",
and then to include the custom validator you should call the Validator::resolver in your AppServiceProvider to bind your custom validator.
public function boot()
{
// Schema::defaultStringLength(191);
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}
Related
In my input form, I have two fields; momentFrom & momentTo. I need to put a validation which gives error message if any of the following criteria fails.
momentFrom is greater than or equal to momentTo.
momentFrom is less than now.
My code for storing the data:
public function store(Request $request, Requisition $requisitionObj) {
$momentFrom = strtotime($request->txtTravelDate . " " . $request->txtTimeFrom);
$momentTo = strtotime($request->txtTravelDate . " " . $request->txtTimeTo);
$timeValidation = $requisitionObj->validateTiming($momentFrom, $momentTo);
if ($timeValidation['error']) {
echo 'ERROR: ' . $timeValidation['message'];
return view('requisitions.create');
} else {
/* store form data into requisition object */
$requisitionObj->travel_date = $request->txtTravelDate;
$requisitionObj->moment_from = $momentFrom;
$requisitionObj->moment_to = $momentTo;
$requisitionObj->save();
return redirect()->route('requisitions.index');
}
}
I have seen laravel custom validation rules where only one field can be validated at a time. But in my scenario I need to check both fields at a time depending on each other. How can I achieve this?
Thanks for any help in advance!
Creating new Rule Class
You can create your custom rule with the artisan command: php artisan make:rule YourRuleNamethis will create a new Rule Class file into the Rules folder.
By default the created file contains a constructor, a passes method and a message method.
Rules Logic
If you have some complicated rules where you need the request or some models, you can pass them via the constructor.
public function __construct(Request $request, User $user, ....)
{
//save them into class variables to access them later
$this->request = $request;
$this->user = $user;
}
Otherwise you can directly put your validation logic into the passes method:
public function passes($attribute, $value){
//some code
return #myCondition
}
Last you are able to specify the message if the validation fails.
public function message()
{
return 'Your message';
}
To use your rule simply add it to your rules array:
$rules = [
'my_attribute' => [new MyCustomRule(),...],
]
At last, I have solved this problem using FormRequest and AppServiceProvider. Thought this would help others who come to this place.
First I have created FormRequest validator using following artisan command.
php artisan make:request StoreRequisition
Then added primary validation rules and messages into it.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequisition extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
$rules = [
'txtTravelDate' => 'required|date_format:Y-m-d|after_or_equal:today',
'txtTimeFrom' => 'required|date_format:H:i|travel_time_validate',
'txtTimeTo' => 'required|date_format:H:i',
];
return $rules;
}
public function messages() {
return [
'txtTravelDate.required' => 'Travel date is required!',
'txtTravelDate.date_format' => 'Invalid format for Travel Date!',
'txtTravelDate.after_or_equal' => 'Travel Date should be today or later!',
'txtTimeFrom.required' => 'Time From is required!',
'txtTimeFrom.date_format' => 'Invalid format for Time From!',
'txtTimeFrom.travel_time_validate' => 'Invalid time selected!',
'txtTimeTo.required' => 'Time To is required!',
'txtTimeTo.date_format' => 'Invalid format for Time To!',
'listFunction.required' => 'Department to be selected!',
'txtPickLoc.required' => 'Pickup Location is required!',
'txtDropLoc.required' => 'Drop Location is required!',
'listPurpose.required' => 'Travel Purpose to be selected!'
];
}
}
Then inside app\Providers\AppServiceProvider, added the extra validation logic.
public function boot() {
Validator::extend(
'travel_time_validate',
function ($attribute, $value, $parameters, $validator) {
$inputs = $validator->getData();
/* convert time to moments */
$momentFrom = strtotime($inputs['txtTravelDate'] . " " . $inputs['txtTimeFrom']);
$momentTo = strtotime($inputs['txtTravelDate'] . " " . $inputs['txtTimeTo']);
$result = true;
if ($momentFrom >= $momentTo) {
$result = false;
}
return $result;
}
);
}
My Controller:
public function store(StoreRequisition $request, Requisition $requisitionObj) {
$validatedData = $request->validated();
/* store form data into requisition object */
$requisitionObj->requester_id = Auth::user()->id;
$requisitionObj->travel_date = $request->txtTravelDate;
$requisitionObj->time_from = $request->txtTimeFrom;
$requisitionObj->time_to = $request->txtTimeTo;
$requisitionObj->purpose_id = $request->listPurpose;
/* Finally save the record into the database */
$requisitionObj->save();
return redirect()->route('requisitions.index');
}
Example how make custom rule for validation in Laravel 8.x / Lumen 8.x.
public static function rules(){
return [
'number' => [
'required', 'min:1', 'max:30', 'string', self::testNumber(),
],
];
}
public static function testNumber(){
return function($attribute, $value, $fail){
if ($value === 'foo'){
$fail('The '.$attribute.' is invalid.');
}
};
}
I want check if my form value equals in database value in laravel
Here is my controller class
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id , 'sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
What i do wrong?
update to
DB::table('users')->where(['id',$id ])->where([ 'sms_token_in'
,$sms_token])->update(['sms_verify'=>'1' ]);
The most simple way to use where is
two parameters, 1: database field name, 2: value
three parameters (field name, operator, value) ('1', '>=', 3)
DB::table('users')->where('id',$id)->where('sms_token_in', $sms_token)->update([
'sms_verify'=>'1'
]);
Try
DB::table('users')->where([
['id',$id],
['sms_token_in', $sms_token]
])->update([
'sms_verify'=>'1'
]);
First you must accept two parameter from your function. Look like only you are passing only one.
change function parameter to
public function code_post(Request $request, $id = 0)
then
if(!empty($id)){
User::where(['id' => $id,'sms_token_in' => $sms_token])->update([
'sms_verify'=>'1'
]);
}
// you can do this in two way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id)->where('sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
//2nd way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where(['id',$id , 'sms_token_in' ,$sms_token])->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
The best whey to do it is on Validators in laravel so, if it don't exist create a classe validator that extends "LaravelValidator" and do it:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'sms_token_in' => 'required|unique:your_table_name',
],
ValidatorInterface::RULE_UPDATE => [],
]; protected $messages = [
'sms_token_in.unique' => 'Your duplicate message!'
];
In your controller instantiate your validator in construct like it:
public function __construct(MyValidatorClass $validator)
{
$this->validator = $validator;
}
And in your controller function store do it, before your persist on database.
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
In this way, you can use validator from Laravel to check and return anything you want to your user.
function check(Request $request){
//validate
$request->validate([
'email'=>'required|email',
'user_pass'=>'required|min:5|max:12'
]);
$userInfo=Employee::where('email','=',$request->email)->first();
if(!$userInfo){
return back()->with('fail','We do not recognize your email address');
}else{
//check password
if($request->user_pass=$userInfo->user_pass){
$request->session()->put('LoggedUser', $userInfo->emp_id);
return redirect('/employee/dashboard');
}else{
return back()->with('fail','Incorrect password');
}
}
}
In this method im check if the user_pass from request is equal to $userInfo->user_pass that query from database.
if($request->user_pass=$userInfo->user_pass)
I need to check some special validation in my action store
public function store(Request $request) {
$this->validate($request, [
'practice'=>'required|max:100',
'project'=>'required',
'work_place'=>'required',
'telephone_1'=>'required',
'date_recurring_for_beginning' => 'required|date',
'date_recurring_for_end' => 'required|date|after_or_equal:date_recurring_for_beginning',
]);
RequestCollaborator::create($request->all());
return redirect()->route('requestsCollaborator.index')
->with('flash_message',
trans('request.request_created'));
}
I have to validate if the difference between date_recurring_for_beginning and date_recurring_for_end is 3 months?
there is any solution for doing this or I have to create a custom validation?
You can use Validator::extend() and can create your custom validation rule. Like
Validator::extend('valid_date_range', function ($attribute, $value, $parameters, $validator) {
$dateBeginning = \Carbon::createFromFormat('Y-m-d', $parameters[0]); // do confirm the date format.
$dateEnd = \Carbon::createFromFormat('Y-m-d', $value);
return $dateBeginning->diffInMonths($dateEnd) == $parameters[1];
});
You can use this like:
'date_recurring_for_end' => 'required|date|valid_date_range:date_recurring_for_beginning,3'
For more details about the custom validation. Please follow the documentation.
https://laravel.com/docs/5.8/validation
Create a custom validation rule within your app/Providers/AppServiceProvider:
public function boot()
{
Validator::extend('date_difference', function ($attribute, $value, $parameters, $validator) {
$firstDate = Carbon::parse($parameters[0]);
$secondDate = Carbon::parse($parameters[1]);
$minDifference = (int)$parameters[2];
if($firstDate->diffInMonths($secondDate) < $minDifference)
return false;
return true;
});
}
To use this rule:
$this->validate([
'some_field' => 'date_difference:date_one,date_two,3',
]);
Hope it helps.
I have a form that contains a field for user to enter amount value of certain payment. This field is input of type number.
The validation rule in Laravel for this input is:
'amount' => 'required|numeric'
When I enter the amount in English as: 1500 => The validation passes and everything is OK.
But when I enter the amount in Arabic as: ١٥٠٠ => The validation fails with the following error message:
"validation.numeric"
Should I validate this field manually or is there another solution to this problem?
Maybe you can create your own validation type.
You can add something like this to your boot method in app/Providers/AppServiceProvider.php.
Validator::extend('arabic_numbers', function ($attributes, $value, $parameters, $validation) {
$arabic_numbers = [
'٥',
'١',
// add more
];
$input = $value;
if (!$input) {
return false;
}
$chars = preg_split('//u', $input, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $char) {
if (!in_array($char, $arabic_numbers)) {
return false;
}
}
return true;
});
You can add to your existing rule, e.g. required|arabic_numbers.
Or use something like this:
$input = '١';
$validator = Validator::make([
'user_input' => $input,
], [
'user_input' => 'required|arabic_numbers'
];
if ($validator->fails()) {
//
}
Also you can use in many other ways for example in a custom request:
public function rules()
{
return [
'something' => 'required|arabic_numbers',
];
}
Hope this helps.
Just trying to do some tags validation. First checking for number of tags (as comma separated list of id's).
class SomePostRequest extends Request
{
public function rules()
{
return [
'tags' => 'between:2,5'
];
}
public function all()
{
$input = parent::all();
$input['tags'] = explode(',', #$input['tags']);
return $input;
}
}
It keeps spititing out the message as
The tags must be between 2 and 5 characters.
Instead of the proper array message:
The :attribute must have between :min and :max items.
Try to use custom validation rule for you requirement:
$this->app['validator']->extend('tag', function ($attribute, $value, $parameters)
{
$tags = explode(',', $value);
if(count($tags) >= 2 || count($tags) <= 5)){
return false;
}
});
and then rules would be
public function rules(){
return [
'tags' => ['tag']
];
}
and message can update by
public function messages() {
return [
'tags.tag' => 'The :attribute must have between :min and :max items.'];
}
I hope, you get basic idea to achieve this requirement, let me know if its helps.