user3287550 user3287550 - 3 months ago 64
HTML Question

setCustomValidity Bootstrap keep error popup

I've implement localization in my application, all this stuff is saved inside a php file. So I can easy do this:

<input class="form-control" type="text" required="" placeholder="username" oninvalid="this.setCustomValidity('<?php echo $this->lang->line('field_required'); ?>')"></input>


Now if I doesn't enter any text I can see the custom message, but if I fill the input I see again the popup as the form can't get the text inside.

It's a bug of Bootstrap?

EXAMPLE

https://jsfiddle.net/DTcHh/23662/

Answer

Using the onvalid won't work in some browsers like Safari or IE below 10. Use a custom event notifier for attaching the function.

Note: As you mentioned in the comment you can print the message from the data-invalid-message attribute from php and catch it using jQuery by .data('invalidMessage').

SEE WORKING EXAMPLE:

var myobj = jQuery('input.form-control');
myobj.on('keyup keypress blur change input', function() {
  var messg = ($(this).data('invalidMessage'));
  if (this.validity.typeMismatch) {
    this.setCustomValidity(messg);
  } else {
    this.setCustomValidity('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<form>
  <input class="form-control" type="email" required placeholder="username" data-invalid-message="custom message from php here">
  <button type="submit">
    go
  </button>
</form>