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

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' => 'クレジットカード',
],

Related

Laravel 9 required_if not validating

I'm using Laravel 9 and Livewire 2.0
I have an integer field called 'new_weight' that should validate required if the boolean checkbox 'stripped' is selected. Although 'stripped' is not selected, it's still validating as required. The validation $rules are being hit because if I remove the rule, it doesn't validate at all.
I also recently noticed that if I die and dump '$this->stripped' when the checkbox is selected, it dumps 'true' to the console and not '1', but if I leave unchecked, it dumps '0'--not sure if this matters.
edit.php
...
protected $rules = [
'car_color' => 'required|string',
'new_weight' => 'required_if:stripped,accepted|integer|min:1|max:999',
];
protected $messages = [
'car_color' => 'Please enter car color.',
'new_weight' => 'New Weight Value must be great than 1 but less than 999'
];
...
edit.blade.php
...
<div class="flex items-center h-5">
<input wire:model.defer="stripped" id="stripped" name="stripped"
wire:click="updateStripped"
type="checkbox">
</div>
<div>
<input wire:model.defer="new_weight" id="new_weight" name="new_weight"
type="text"
placeholder="New Vehicle Weight in lbs:">
</div>
...
Since stripped itself is not a rule, I would consider using a custom callback to evaluate the stripped input.
'new_weight' => [
Rule::requiredIf(function () use ($request) {
return $request->input('stripped');
}),
'integer|min:1|max:999'
]
I have this problem too, so I use Rule::when like this and get me same result:
[Rule::when(this->stripped == 'accepted', 'required|integer|min:1|max:999')]
when condition ( this->stripped == 'accepted' ) is true, the rules run
of course if stripped is a check box, you must find out what that's return, so first use dd for that, then replace that with 'accepted' ( I think check box return true and false )
The new_weight field had a default null value in the database. Once I re-migrated with a default empty value, my problem was solved.

Laravel 5.6: Skip validation step if field exists and isn't changed. If field IS changed it is Required - but not unique

I have situation where an admin edits an employee form: The first name, last name, and SSN are required on ADDING an employee. No problems there. Where I have an issue is when EDITING the form. I have no problem validating the SSN as it is a unique field.
'ssn_edit' => 'required|unique:employees,ssn,' . $id
But what I DO have an issue with is the non-unique fields. I don't know how to set the validation to skip by ID when the field is NOT unique. Here is the entire rules section of the FormRequest:
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|unique:employees,ssn,' . $id
];
}
Obviously - this throws the validation error on first_name and last_name regardless if the field is populated or not.
Any help some of you Laravel gurus can throw my way would be GREATLY appreciated!
There is so many tricks you can do to solve the problem. But I only got two ways..
The first is: Prevent to send your ssn_edit value when you want to edit the employee
example:
<input type="text" value="{{ isset($employee) ? $employee->ssn_edit : old('ssn_edit') }}" #isset($employee) disabled #endisset name="ssn_edit">
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|sometimes|unique:employees,ssn,' . $id
];
}
The second is: Check your method before validate the employee.. is it POST or PUT, if it's PUT don't add the unique rule in your validation.
Conclusion: The validation will work every time you call the validation, no matter if you edit or add new employee. #CMIIW
You mustn't have error with validating non-unique fields, probably you have wrong edit form, set value attribute to input like
<input type="text" value="{{ $employee->first_name }}" name="first_name">

Laravel custom validation attribute names with wildcards

When customising Laravel 5.7 validation attributes, is it possible to include wildcards in the attribute names? I can't determine the correct way to indicate a wildcard here.
I have a contacts page which lists the details of a particular contact including all of their phone numbers and emails. From this page you can edit each of these, and add new ones. As such I've used a foreach statement to display each of these and included their id numbers in the form field names, ie:
phone_areacode_{{ $number->id }}
phone_number_{{ $number->id }}
phone_extension_{{ $number->id }}
This makes their names unique and means I can display the error messages relevant only to the specific number or email being edited when validation fails. However, the error messages that display include the number so I get things like "The phone areacode 10 format is invalid." or "The phone number 27 may not be greater than 20 characters."
Is there a way to use wildcards in the attribute names when defining them in the validation language file? Basically I'd like to be able to do this:
'attributes' => [
'phone_areacode_*.*' => 'phone areacode',
],
If not, how can I define the attribute names in the #update method of my controller?
Post values using arrays/objects, and specify validation rules/lang using dot notation:
Example POST data:
{
"phone": {
"ID1234": {
"areacode": "123",
"number": "1231234",
"extension": "1"
}
}
}
Example HTML form (equivalent to POST data above):
<form action="?" method="post">
<input name="phone[ID1234][areacode]" />
<input name="phone[ID1234][number]" />
<input name="phone[ID1234][extension]" />
<input type="submit">Submit</input>
</form>
Example validation:
$validator = Validator::make($request->all(), [
'phone.*.areacode': 'required',
'phone.*.number': 'required',
'phone.*.extension': 'required',
]);
Example lang file:
return [
'attributes' => [
'phone.*.areacode': 'phone area code',
'phone.*.number': 'phone number',
'phone.*.extension': 'phone extension',
],
]);
do you try this way it's from Laravel documentation
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],

Laravel: How to make a field required only if another specific field exists?

I have a form that asks for several files, and description of these files. Something like
<input type="file" name="file1">
Describe your file:
<input type="text" name="desc1">
I want the user to describe the contents of the file, instead of only showing something like Invoices-final-FinalV30.docx he might say "Invoices for January, 2018", so when I validate the form, I know how to ask if a field follows a regex, or if the field is required and so on, using the validate() method, but I want something custom, something that makes "desc1" required ONLY if there's a "file1", if there's no "file1" I can safely ignore whatever "desc1" carries.
Try required_with:anotherfield validation
https://laravel.com/docs/5.7/validation
$validator = Validator::make(
$request->all(),
[
'file1' => 'mimes:jpeg,bmp,png', //your file validation
'desc1' => 'bail|required_with:file1' //add other description validations
]
);
For array fields, example named upload[][file] , upload[][desc]
$validator = Validator::make($request->all(), [
'upload.*.file' => 'mimes:jpeg,bmp,png',
'upload.*.desc' => 'bail|required_with:upload.*.file',
]);

Yii2 ActiveForm encodeErrorSummary property... what is it intended for?

I was trying to use the Yii2 ActiveForm encodeErrorSummary property because I wanted to put line-breaks on Yii2 validation error messages:
Example code snippet in MODEL file
public function rules()
{
return [['username', 'required', 'message' => 'long message first line here<br> long message last line here']];
}
Example code snippet in VIEW file
$form = ActiveForm::begin(['id' => 'myform',
'encodeErrorSummary' => false
]);
...
echo $form->field($model, 'username');
...
ActiveForm::end();
Official Yii2 Documentation describes encodeErrorSummary property as:
Whether to perform encoding on the error summary.
but it seemed not suitable for that in my case... Maybe it's me misunderstanding something (...error summary)?
So... what is it intended for, then?
Thank you!
It seems like you need to configure the $fieldConfig property like this:
ActiveForm::begin([
'fieldConfig' => [
'errorOptions' => ['encode' => false],
],
]);
for your requirement. The errorSummary is the summary that you echo with
<?= $form->errorSummary($model) ?>
before or after the form. What you want is a behavior at the field level, while this is an option to disable the encoding at the summary level.

Categories