Search code examples
jquerytwitter-bootstrapbootstrapvalidator

Bootstrap validator - Place error message on placeholder


How to place the Bootstrap validator error message inside the input placeholder?

I tried errorPlacement but it seems to get no effect.

jsFiddle

 $('.js-form').validator({
            disable: false,
            errorPlacement: function(error, element) {
                if(element.length) {
                    element.attr("placeholder", error.text());
                }
            }
        });

Solution

  • A possible solution is to save the placeholders and handle the submit button:

    $(function () {
      // save placeolders....
      $('.js-form').find(':input').each(function(index, ele) {
        $(ele).attr('placeholderSaved', $(ele).attr('placeholder'));
      });
      
      $('.js-form').validator({disable: true}).on('submit', function (e) {
        $('.js-form').find('div.with-errors').each(function(index, element) {
          var cacheEle = $(element);
          var errMsg = cacheEle.find('li').text().trim();
          
          // on error change placeholder with error message
          if (errMsg.length > 0) {  
            cacheEle.hide().prev().attr('placeholder', errMsg);
          } else {
            // on success restore placeholder
            cacheEle.hide().prev().attr('placeholder', cacheEle.hide().prev().attr('placeholderSaved'));
          }
        });
      });
    });
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
    
    
    
    <div class="container">
        <div class="row">
            <div class="col-md-5">
    
                <form class="js-form" data-toggle="validator" role="form">
                    <div class="form-group">
                        <label for="inputName" class="control-label">Name</label>
                        <input type="text" class="form-control" id="inputName" placeholder="Name" required>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
                        <div class="help-block with-errors"></div>
                    </div>
    
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
    
            </div>
        </div>
    </div>