英文:
Laravel 8: min & max validation depends on the previous selected
问题
在应用程序中,有一个名为“Products”的配置,其中一些字段是:最小金额和最大金额。
在注册模块中,字段为:产品和金额。用户将选择要购买的产品种类。金额不应小于最小金额,但也不应大于最大金额。
例如
在我的产品中,我有以下内容:
产品1:
最小金额:$5,000
最大金额:$50,000
产品2:
最小金额:$500
最大金额:$4,500
用户选择产品1,
金额:500
一旦用户保存,将会出现错误消息,“金额不应小于xxx”或“金额不应大于xxx”。
问题:是否可以使Laravel验证的最小和最大值依赖于所选的产品?
更新的帖子
Laravel验证
$this->validate([
'amount' => 'required|min:xx|max:xx',
]);
Products表格
id
名称
最小金额
最大金额
英文:
In the application, there is a configurations called "Products" where some of the fields are: minimum amount and maximum amount.
In the registration module, fields are: products & amount. The user will choose what kind of product they will avail/buy. The amount should not be less than the minimum amount but not greater than the maximum amount.
For example
In my Products I have the ff:
Product 1:
Minimum Amount: $5,000
Maximum Amount: $50,000
Product 2:
Minimum Amount: $500
Maximum Amount: $4,500
User choose Product 1,
Amount: 500
Once the user clicked the saved, there will be an error, "amount should not be less than to xxx" or "amount should not be greater than to xxx"
Question: Is it possible to make the min & max of laravel validation depends on the selected of the products?
UPDATED POST
Laravel validation
$this->validate([
'amount' => 'required|min:xx|max:xx',
]);
Products table
id
name
minimum_amount
maximum_amount
答案1
得分: 2
在Livewire中,你有两种选项来定义组件的规则(在Livewire v3中使用新的属性方法有三种选项)。然而,只有其中一种是动态的,这是你需要的。由于你没有提供任何代码,我假设你有一个$productId
和一个计算属性用于获取产品。
要在Livewire中实现动态规则,使用rules()
方法(不要使用protected $rules = []
属性)。
class Product extends Component
{
public $productId;
public $amount;
public function getProductProperty()
{
return Product::find($this->productId);
}
protected function rules()
{
$product = $this->product;
$rules = [
'amount' => ['required'],
];
if ($product->min_amount) {
$rules['amount'][] = 'min:' . $product->min_amount;
}
if ($product->max_amount) {
$rules['amount'][] = 'max:' . $product->max_amount;
}
return $rules;
}
}
英文:
In Livewire, you have two options to define rules of the component (three options in Livewire v3 with the new Attribute approach). However only one of them is dynamic, and this is what you'll need. Since you haven't provided any code, I'll assume that you have an $productId
and a computed property for obtaining the product.
To achieve dynamic rules in Livewire, use the rules()
method (and do not use the protected $rules = []
attribute).
class Product extends Component
{
public $productId;
public $amount;
public function getProductProperty()
{
return Product::find($this->productId);
}
protected function rules()
{
$product = $this->product;
$rules = [
'amount' => ['required'],
];
if ($product->min_amount) {
$rules['amount'][] = 'min:'.$product->min_amount;
}
if ($product->max_amount) {
$rules['amount'][] = 'max:'.$product->max_amount;
}
return $rules;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论