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

Asked

Viewed 51 times

1

I need to test if a date-* attribute exists in 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’s the safest way to do this validation with Javascript?

1 answer

3


Only test if the method getAttribute returns something.

Example code (change the element ids to be able 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" /> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.