Laravel Required If Two Conditions

Laravel has a feature called “Conditional Validation Rules” that allows you to specify certain validation rules only if certain conditions are met. This is done using the `required_if` rule, which requires a field to be filled out if another field meets a specified value or condition.

Here’s an example to illustrate this concept:

<form action="/example" method="POST">
    <label for="role">Role:</label>
    <select name="role" id="role">
        <option value="admin">Admin</option>
        <option value="user">User</option>
    </select>

    <div id="admin-section">
        <label for="admin_code">Admin Code:</label>
        <input type="text" name="admin_code" id="admin_code">
    </div>

    <input type="submit" value="Submit">
</form>

<script>
document.getElementById('role').addEventListener('change', function() {
    var adminSection = document.getElementById('admin-section');

    if (this.value === 'admin') {
        adminSection.style.display = 'block';
        adminSection.querySelector('input').setAttribute('required', 'required');
    } else {
        adminSection.style.display = 'none';
        adminSection.querySelector('input').removeAttribute('required');
    }
});
</script>
    

In this example, we have a form with a dropdown select field for specifying the user’s role. If the role selected is “Admin”, an additional field for the admin code is displayed, and this field is required. If any other role is selected, the admin code field is hidden and not required.

By using JavaScript, we listen to the change event of the role select field. If the selected value is “admin”, we display the admin code field and mark it as required. If the value is anything else, we hide the admin code field and remove the required attribute.

This way, the admin code field will only be required if the user selects “Admin” as their role.

Read more interesting post

Leave a comment