Question :
I need to validate a form using the browser with the required
property. Only that there is a problem, my submit button is not on the form. It has to stay out, and when I click on it I call $('form[name="meu_form"]').submit()
and when I do this it does not validate using the browser.
Example:
HTML
<!-- HTML -->
<form name="meu_form">
Teste campo: <input type="text" name="teste" required />
<br />
<button type='submit'>Enviar que valida o required</button>
</form>
<button class='btnSubmit'>Enviar que não funciona a validação do required</button>
Javascript
//Javascript
$(function(){
$('form[name="meu_form"]').submit(function () {
alert('Aqui faço as chamadas ajax...');
});
$('.btnSubmit').click(function (){
$('form[name="meu_form"]').submit();
});
});
The problem occurs in the following scenario:
If I leave the input
empty and click the button inside the form
, it validates, if I click on the outside it just goes by. Is there a way to validate this using the same validation of HTML
, or do I really have to validate at hand, or do not know, use a plugin for example jQuery Validator?
Answer :
I said, it’s kind of like a game but it worked!
First I create the button inside the form with
display
none
After this I put the button outside and call the .click with jquery in the element that I put display none.
Follow the code below to see how it went:
HTML
<!-- HTML -->
<form name="meu_form">
Teste campo: <input type="text" name="teste" required />
<br />
<button type='submit' class='btnOrig' style='display: none;'>Enviar que valida o required</button>
</form>
<button class='btnSubmit'>Enviar que não funciona a validação do required</button>
JavaScript
//Javascript
$(function(){
$('form[name="meu_form"]').submit(function () {
alert('Aqui faço as chamadas ajax...');
return false;
});
$('.btnSubmit').click(function (){
$('.btnOrig').click();
//$('form[name="meu_form"]').submit();
});
});
Note: I put an example in the JSFiddle link: link
There is a checkValidity
method that is part of the HTML5 API . With it you can make the browser check the element. Not the whole form, but at least the elements one by one.
So in your code you can:
$('.btnSubmit').click(function (){
var form = $('form[name="meu_form"]');
var input = form.find('input[name="teste"]').get();
if (input.checkValidity()) form.submit();
else alert('Erro!');
});
Associate the button with your form indicating a id
to form
and calling it in button
as per the code below:
<form name="meu_form" id="myForm">
Teste campo: <input type="text" name="teste" required />
<br />
<button type='submit'>Enviar que valida o required</button>
</form>
<button class='btnSubmit' form="myForm">Enviar que não funciona a validação do required</button>