首页 > 解决方案 > laravel 验证,如何在客户端添加验证规则?

问题描述

//html code
<form>
<input type="radio" id="defult" name="price_type" value="default">
<label for="defult">Default Price</label><br>
<input type="radio" id="custom" name="price_type" value="custom">
<label for="custom">Custom Price</label><be>

<input placeholder="Custom Price" class="form-control" name="custom_price">
</form>

$('input[type=radio][name=price_type]').change(function() {
    if (this.value == 'default') {
        //make custom_price optional
    }
    else if (this.value == 'custom') {
        //make custom_price required
    }

});

实际上,我有一个用于自定义价格或默认价格的单选框,如果用户选择自定义价格,则希望 input[name=custom_price]必需,或者如果用户选择默认价格,则使 input[name=custom_price]可选

标签: javascriptjquerylaravelvalidationlaravel-5

解决方案


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form>
        <input type="radio" id="default" name="price_type" value="default">
        <label for="default">Default Price</label><br>
        <input type="radio" id="custom" name="price_type" value="custom">
        <label for="custom">Custom Price</label><br>
        <input placeholder="Custom Price" class="form-control" name="custom_price" required>
        <input type="submit" value="Submit">
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $('input[type=radio][name=price_type]').change(function() {
        if (this.value == 'default') {
            //make custom_price optional
            $('input[name=custom_price]').prop('required', false);
        }
        else if (this.value == 'custom') {
            //make custom_price required
            $('input[name=custom_price]').prop('required', true);
        }
    });
    </script>
</body>
</html>


推荐阅读