How to appear required in an input without form?

Asked

Viewed 435 times

1

I wanted to make a form but without using <form> because I intend to send the inputsfor ajax. The problem is that if you take the form, it will not be required because as you have said in W3schools

The attribute required specifies that a input must be filled before to be submitted

So, what can I do to get it? I searched and found this code:

document.getElementById('put_id_here').validity.valid;

But the above code did not work.

  • 1

    This works well https://jsfiddle.net/Sergio_fiddle/97k5n5yj/ what is the problem you are having?

  • Try adding a button <button>. I tried and gave no reply

  • I had the ill-defined id on what I tried but I wanted him to give Trigger to the required, and not say whether it is empty or not

  • @I_like_trains ok, if you want to use the native UI this doesn’t work without form.submit. You can make your own, using the .validity.valid. But if you want it to be automatic via browser use <form> and then prevents it from being submitted with e.preventDefault();

  • @Sergio On second thought, I think I’ll just change the color of the border to red with a more simple and pleasant side warning. Post your answer and I’ll accept it.

  • @I_like_trains done. I’ve put together one more idea that might be useful: :empty of the CSS

Show 1 more comment

2 answers

3


You can use the selector :invalid to apply CSS to the non-validated input. The only drawback is that the CSS loads right from the start. So you can add a class to join the element when you first receive focus.

var input = document.getElementById('put_id_here');
var button = document.querySelector('button');
var info = document.querySelector('p');

input.addEventListener('focus', function() {
  this.classList.add('validate');
});

button.addEventListener('click', function() {
  if (input.validity.valid) {
    info.textContent = 'Tudo OK!';
  } else {
    info.textContent = 'O input tem de ser preenchido!';
  }
});
.validate:invalid {
  border: 1px solid red;
}
<input type="text" id="put_id_here" required>
<button>Enviar</button>
<p></p>

  • Could you explain to me this validity.valid inside the code? The name is very suggestive but I can’t find words to explain hehehe

  • @Leocaracciolo would be more or less: input.validador.valido, namely the input.validity is an Object Validitystate containing a number of values related to the validation status of the input.

0

You can put it like this.

<form action="javascript:enviar();"> 
   <input type="text" name="text" required>
</form>

<script>

    function enviar() {
        var text = document.getElementsByName('text')[0].value;
        alert( text );
    }

</script>

Browser other questions tagged

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