exhtml
2/6/2018 - 1:00 PM

Basic HTML5 Pattern Validation on custom event (blur, etc)

Las validaciones HTML5 solo se aplican onSubmit del formulario. Aqui mostramos una forma de lanzar las validaciones nativas HTML onBlur utilizando el método nativo JS 'checkValidity()' https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation

Useful pattern regexps: http://html5pattern.com/

<div class="form-group">
    <label for="reportName">Name</label>
    <input type="text" class="form-control" name="reportName" value="" data-js="report-name-field" 
      placeholder="Nombr del report..." 
      required 
      pattern='[^\\/:\*\?"<>\|,]+' 
      title='Los siguientes caracteres no estan permitidos: \ / : ? * " < > |'
    /> 
    <span class="help-block"></span>     
</div>

var $reportNameField = $('[data-js="report-name-field"]');

$reportNameField.on('blur', function(){
  var self = $(this);
  var value = self.val();
  var message = self.attr('title');
  
  if(value.length && !self[0].checkValidity()) { //checkValidity is native JS (so we need the dom element inside jquery selector) and refers to html5 'pattern' attribute
      self.parent().addClass('has-error'); //add class to form-group  
      self.next().text(message); //fill the <span> help-block with the validation text
  } else {
      self.parent().removeClass('has-error');
      self.next().empty();
  }
  
});