What is the safest way to test if a data-* attribute exists?

1

I need to test if a data-* attribute exists on an element and if that attribute is filled with some value:

<input type="text" id="teste" data-validationMessage="Esse campo é obrigatório" /> <!-- Deve retornar true -->

<input type="text" id="teste" data-validationMessage="" /> <!-- Deve retornar false -->

<input type="text" id="teste" /> <!-- Deve retornar false -->

What is the safest way to do this validation with JavaScript?

    
asked by anonymous 21.03.2017 / 20:54

1 answer

3

Only test if the getAttribute method returns something.

Sample code (change the ids of the elements in order to execute the snippet.

validaDataAttribute(document.getElementById('teste'));
validaDataAttribute(document.getElementById('teste2'));
validaDataAttribute(document.getElementById('teste3'));

function validaDataAttribute(input){
  var dataAttr = input.getAttribute('data-validationMessage');
    
  if(dataAttr){
    console.log(input.id + ' contém o atributo data-validationMessage com um valor');
  }
}
<input type="text" id="teste" data-validationMessage="Esse campo é obrigatório" />
<input type="text" id="teste2" data-validationMessage="" /> 
<input type="text" id="teste3" /> 
    
21.03.2017 / 21:06