Front-end validation for required field, conditional to value of radio button

Viewed 244

I have a Laravel Blade form where I make the fields required like this:

<input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>

                            @error('name')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror

This works, and when I try to submit the form with no name value, I get this error:

enter image description here

But, now I have a radio button, and another field called postal_code:

<input type="radio" name="billing_type" class="billing_type" value="paypal" checked /> PayPal
<input type="radio" name="billing_type" class="billing_type" value="card" /> Credit Card

<input type="text" class="form-control" name="postal_code" value="{{ old('postal_code') }}" placeholder="" />

How do I make the postal_code field required, but only if the radio button is set to the value card?

I can handle the validation in the back-end, but I want the front-end validation in blade, like I have for the name field above.

1 Answers

You can make it with jquery, add an attribute required if the value is a card. otherwise, remove it.

$('.billing_type').change(function() {
    var type = $(this).val();
    if(type == 'card'){
        $('.postal_code').attr("required","required");
    }else{
        $('.postal_code').removeAttr("required");
    }
});
Related