Laravel validation : different messages with the same rule - laravel

I have a validate like this :
if ($a > $b) {
$rule['to'] = 'required|date_format:Y-m-d H:i:s|after:from';
else {
$rule['to'] = 'required|date_format:Y-m-d H:i:s|after:now';
}
Can i have the two different messages like:
'to.after:from' => 'aaaaaaaaaaaa',
'to.after:now' => 'bbbbbbbbbbb',
Sorry my message is japanese so i don't up here.
I want to know if it has the way to show two messages with the same rule.
I tried to change the defaul message of laravel
'after'=> 'The :attribute must be a date after :date.',
but didn't work.
Please help me.
Thank so much!

I have checked your query in my example demo. I think Laravel cannot prived for the multiple attribute validation.
So here you can just Do as you done.
'to.after' => 'Your message',
You can create a Request to handle the validation separately from the controller

Related

How can I validate GET controller params in CakePHP 2?

Given this on the model:
public $validate = [
'amount' => array(
'rule' => array('comparison', '>=', 0),
'message' => 'You must buy over 0 of this item!'
)
];
How can I validate param #2 of the below?
public function buy(int $item, int $amount) {
Validation seems to be built only for POST, which I'd like to opt out of here.
First things first, modifying the database with GET requests is an anti-pattern for many different reasons. Even if you assume a friendly user agent (which you never should!), browsers can behave quirky and do unexpected stuff like for example sending GET request multiple times (that is perfectly valid as GET is not ment to modify data), which they usually won't for POST/PUT/DELETE.
I would strongly suggest to change your endpoint to handle POST requests instead.
That being said, you can generally validate whatever you want, the validation mechanisms first and foremost just validate data, they don't know or care where it stems from. You can hand over whatever data you want to your model, and let it validate it:
$data = array(
'item' => $item,
'amount' => $amount,
);
$this->ModelName->set($data);
if ($this->ModelName->validates()) {
// data is valid
} else {
// data is invalid
$errors = $this->ModelName->validationErrors;
}
Moreover you can use CakePHP's validation methods completely manually too:
App::uses('Utility', 'Validation');
$isValid = Validation::comparison($amount, '>' 0);
This example of course doesn't make too much sense, given that $isValid = $amount > 0 would do the same, however it should just show that you can validate anything everywhere without models being involved.
See also
Cookbook > Models > Data Validation > Validating Data from the Controller
Cookbook > Models > Data Validation > Core Validation Rules

Customized validation rule on laravel form request validation

I do have a registration form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.
The user input fields in the form are 'quantity', 'rate' and 'discount'.
The populated fields are 'total' and 'bill_amount'.
What i need to validate are :
Check 'total' equal to 'quantity' * 'rate'.
Check 'bill_amount' equal to 'total' - 'rate'
I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.
In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)
Thanks in advance!
After a long time I was able to find this solution.
Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]
public function withValidator($validator)
{
$quanty = $this->request->get("quantity");
$rate = $this->request->get("rate");
$billAmount = $this->request->get("bill_amount");
$validator->after(function ($validator) {
if(($quanty * $rate) != $billAmount) {
$validator->errors()->add('bill_amount', 'Something went wrong with this field!');
}
});
}

Http request and response in codeigniter

I am currently working in codeigniter and I am new to this.
I was wondering how to retrieve the JSON values using API call .
Can anyone suggest me where should I start.
Many Thanks in advance
Pass your array of row to json_encode();example for method of controller is below
public function getUserList() {
header('Content-Type: application/json');
$query = $this->db->get('mytable');
if(count($query) > 0) {
$message = array('status' => 'true' , 'message' => 'Record get successfully' , 'data' => $return );
}else{
$message = array('status' => 'false' , 'message' => 'Record not found.' );
}
echo json_encode($message);
}
Codeigniter does not have an inbuilt HTTP method so you need to use other things in php to achieve this.
There are 2 ways, you can use cURL, but honestly... it's convoluted... but read this: http://php.net/manual/en/book.curl.php
Another method is using stream_context_create() http://php.net/manual/en/function.stream-context-create.php
I strongly suggest using this 2nd one as its much easier to work with (in context with curl..
Much of how you setup your request depends on the API you are referencing with and the kind of requests it allows: GET, POST ... and what kind of header information it requires you to send over as well do they require oAuth header?
There is no 1 bunch of code fits all, I had to create a full custom library to integrate codeigniter into Magento, it took many hours.

Laravel validation - fail when provided with input not defined in rules

Does Laravel validation provide any ways to fail when request contains input keys that are not defined in validation rules? Ex: Validator is instantiated with the following rules: ['name' => 'required', 'email' => 'required|email']. I want validation to fail if $request contains any other keys except name and email (Think of a user POSTing to the route end-point with undesirable data). Is that possible to achieve with simple validation rules?
P.S. I am aware of mass-assignment tricks with Eloquent, however I need to perform strict validation before any data is manipulated / persisted.
No, it's not possible to achieve with simple validation rules but would be easy to add.
All you would need to do is something like the following...
if ( count(request()->except(['name', 'email']) ) > 0) {
return false;
}

Laravel before/after validation message

In Laravel you can make a custom messages for validators. But I found that the prepared messages are little bit wrong. With before and after validation rules, the parameter is converted with strtotime like that said in the documentation.
So if I set rule 'expires' => 'before:+1 year' the rule is working and correct. But if the user inputs a wrong value, Laravel prints the message like that:
The expires must be a date before +1 year
This message is very unclear for the average client. I was expected that the message will be converted with the strtotime also.
There is a clean way to print more clear error message?
You can override the validation messages with a custom ones if you want to.
In the Form Request class, add the following method and change the messages like so:
public function messages()
{
return [
// 'fieldname.rulename' => 'Custom message goes here.'
'email.required' => 'Er, you forgot your email address!',
'email.unique' => 'Email already taken m8',
];
}
Update:
If you want to change the global messages, you can open the validation.php file inside resources/lang/en/validation.php and edit the message there.
You can user AppServiceProvider.php
and you can write your new validation rule there and set your error message in validation.php file
/app/Providers/AppServiceProvider.php
/resources/lang/en/validation.php
Ex:
Validator::extend('before_equal', function ($attribute, $value, $parameters) {
return strtotime(Input::get($parameters[0])) >= strtotime($value);
});
and the message is
'before_equal' => 'The :attribute field is only accept date format before or equal to end date',
Please try this and you can alter this to based on your require.

Resources