Laravel 5 Form Request manually specify field name to be displayed - php

In Laravel's form request, how can I manually assign the field name to be displayed on error?
This is my blade.php file
<input type="text" name="txtConfigKey" id="txtConfigKey" class="form-control" placeholder="Config Key" />
Then on my request file:
public function rules()
{
return [
'txtConfigKey' => 'required'
];
}
Then the output is: "The txt config key field is required."
Notice that it converted the "txtConfigKey" with spaces. Is there a way for me to manually specify what would the field be?
In CodeIgniter, I can do something like this:
$this->form_validation->set_rules('txtConfigKey', 'Config Key', 'required');
Wherein the first parameter is the name of the field and the second parameter is the name of the field that I want to be displayed on the error message.

If you are using form request then there is a method called messages().
You have to override it with your custom error messages like:
public function messages()
{
return [
'txtConfigKey.required'=>'The Config Key is required'
];
}

Related

How to get the validation message in laravel-validation-rules/credit-card

I used the laravel validator for credit card information as per instructed here.
I can finally let it work but my problem is how can I make its result readable by a user. I am also using Laravel validation like this:
public static function validate()
{
$val = [
'card_num' => ['required', 'numeric', new CardNumber],
];
return $val;
}
So, if I clicked the submit button and the field is empty, the result is card numは必須です。 which means card number is required. And if I supply an invalid card number, the result is validation.credit_card.card_length_invalid, how can I make it has the same result as leaving the field empty? I do like this when getting the validation errors in blade php.
<div>
<label>カード番号</label>
<input type="text" name="card_num" id="credit-card" value="{{ old('card_num', $user['card_num']) }}" >
</div>
#if ($errors->has('card_num'))
<p class="alert-error">
{{ $errors->first('card_num') }}
</p>
#endif
UPDATE
I have seen its source file and messages, but I don't want to directly change the vendor files.
I have tried adding the custom in validation.php, but it's not working.
'custom' => [
'validation.card_length_invalid' => '無効なカード長',
'validation.credit_card' => 'クレジットカード',
],
Your array in validation.php is close to correct. Try changing the top-level key to credit_card instead of custom like they have in the source code. I'm not 100% sure, but I don't think this package supports messages in the custom array like the ordinary Laravel rules do. For example:
'credit_card' => [
'card_length_invalid' => '無効なカード長',
'credit_card' => 'クレジットカード',
],

How to customise error message to add ID in Yii?

Currently I am using $form->error($user_model,'password') this function to show error message which gives me output as <div class="errorMessage">Please enter current password</div> but I want to add id in same div. What changes I have to do for that?
To customize error message you have to go to user model and change/add your message to function rules() array.
function rules() {
return [
['password', 'required', 'message' => 'Your custom message'],
];
}
Check CRequiredValidator class for more information.
To apply some custom ID:
$form->error($error_model, 'password', ['id' => 'My-super-custom-id']);
just it will break your error messages output when using yii-js methods.

Laravel 5.2 - validation - One of the fields is required

Take a scenario,
There are 2 fields available in the form.
1) input type file for manual upload.
2) input type = text to enter youtube video url.
is it possible using laravel built-in validations so that validation will be fired if user has left both fields empty!
I have gone through https://laravel.com/docs/5.3/validation but could not find what I wanted.
In your controller, you could do something like this:
$validator = Validator::make($request->all(), [
'link_upload' => 'required|etc|...',
]);
$validator2 = Validator::make($request->all(), [
'file_upload' => 'required|etc|...',
]);
if ($validator->fails() && $validator2->fails()) {
// return with errors
}
Try required-without-all validation rule. As given in documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Assuming your fields name are url and file, your rule would be like below:
$rules = [
'url' => 'required_without_all:file',
'file' => 'required_without_all:url'
];
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
Try this,
In youre update method add this
$this->validate($request, [
'fileName'=>'required',
'urlName'=>'required'
]);
dont forget to set the fillable in your model
protected $fillable = ['fileName','urlName'];
Hope this helps

Validate field in form - check if "product" exists in CakePhp 3

I've got problem with field validation.
I would like to validate form through model. I want to check if field with some value exists.
I would like to block using some titles more than once.
For example
if field "Site" with title "Main" exists in database, you can't validate form.
If it doesn't exist, you can pass it.
I would like to allow user to add just one "Site" with title "Main", but he can add "Site" with any other title in any case.
Have you got some idea how to solve it?
I think you have two options.
(1) Setup an Ajax request to the server.
To do so:
Create a function, that responds to an Ajax request, in your SiteController named checkName()
public function checkName($name) {
// allow ajax requests
$this->request->allowMethod(['ajax']);
// perform your check within the db
$isExistent = [...];
// prepare the response
$response = ['name' => $name, 'isExistent' => $isExistent];
if ($this->request->isAjax()){
$this->autoRender = false;
$this->response->disableCache();
$this->response->type(['json' => 'application/json']);
$this->response->body(json_encode($response));
}
}
Add the route to your routes file with the option '_ext' => 'json'
Prepare your Javascript Ajax function that call the route you have defined and attach it on the onchange attribute of your input field. (see this link for a simple example: http://www.w3schools.com/jquery/ajax_ajax.asp)
(2) Make the 'name' field of the Site table unique.
To do so you could add the following function to your SiteTable class
public function buildRules(
RulesChecker $rules
) {
$rules->add($rules->isUnique(['name']));
return $rules;
}

cakephp3 custom validation

I have a duration field that sometimes can be empty and sometimes can't, depending on the other data sent by the form. So I'm trying to do custom validation in CakePHP3.
In my table I did
public function validationDefault(Validator $validator)
{
$validator
->add('duration', 'durationOk', [
'rule' => 'isDurationOk',
'message' => 'duration is not OK',
'provider' => 'table'
]);
return $validator;
}
public function isDurationOk($value, $context)
{
// do some logic
return false; // Always return false, just for test
}
Now when I set the value for duration field I get an 'duration is not OK' error (as expected). But when I let the value empty I get a 'This field cannot be left empty' error.
So I added:
->allowEmpty('duration');
But in this case when duration is empty I don't get an error at all.
Am I doing something wrong or it's just me don't understanding how validation works?
Let me read the book for you:
Conditional Validation
When defining validation rules, you can use the on key to define when
a validation rule should be applied. If left undefined, the rule will
always be applied. Other valid values are create and update. Using one
of these values will make the rule apply to only create or update
operations.
Additionally, you can provide a callable function that will determine
whether or not a particular rule should be applied:
'on' => function ($context) {
// Do your "other data" checks here
return !empty($context['data']['other_data']);
}
So just define the conditions depending on your "other data" in the callback to apply the rule only when the conditons are true.
Alternatively you can manipulate the plain form data even before it gets validated in the beforeMarshal() callback of the table and change the form data as needed or load another validator or modify the validator.

Categories