Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.0 kB
1
Indexable
Never
var form = $("form").first();
    $("#validate").click(function() {
        var mockResponse = {
            errors :
                {
                    'first_name': 'First name must not be blank',
                    'last_name': 'Last name must not be blank'
                }
        };
        $.each(mockResponse.errors, function(fieldName, error) {
            let field = form.find('[name="' + fieldName + '"]');
            field.addClass("is-invalid");
            let immediateSibling = field.next();
            if (immediateSibling.hasClass('invalid-feedback')) {
                immediateSibling.text(error);
            } else {
                field.after("<div class='invalid-feedback'>" + error + "</div>")
            }

        });
        return false;
    });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="bg-light">

<div class="container">    
    <form id="register-form" novalidate>        
        <div class="form-group">
            <label class="sr-only" for="first_name">First Name</label>
            <input type="text" id="first_name" name="first_name" value="" placeholder="First Name" class="form-control" >
        </div>
        <div class="form-group">
            <label class="sr-only" for="last_name">Last Name</label>
            <input type="text" id="last_name" name="last_name" value="" placeholder="Last Name" class="form-control" >
        </div>
        <div class="form-group">
            <label class="sr-only" for="email">Email Name</label>
            <input type="text" id="email" name="email" value="" placeholder="Email" class="form-control" >
        </div>
        <button id="validate" class="btn btn-primary btn-lg btn-block" type="submit">Validate</button>
    </form>
</div>
Return to post