How to know if all the fields of a form are filled before submitting?

1

I have a form with several fields in which the option 'required' is set. Is there any way to know by DOM if all the fields are filled out before submitting? I mean I want to know if the DOM already contemplates the possibility of indicating if all the fields of a form have been filled out. I do not want to check the fields one by one with javascript.

HTML code:

<form id="form1"> 
  <input id="campo1" type="text" required />
  <input id="campo2" type="text" required />
  <input id="continuar" type="button" onclick="formRellenado();" />
</form>

Javascript code (assuming there was a form method that told you if all the fields are filled in?):

function formRellenado() {
  if (document.forms["form1"].rellenado) {
    // hacer submit con una llamada a servidor mediante asp.net
  }
  else {
    // no hacer submit
  }
}
    
asked by Popularfan 30.11.2018 в 13:37
source

1 answer

0

Since you are using asp.net, why do not you use "requiredfieldvalidator"?

The idea is that you give the id of the control you want to validate. in this case it is called "txt" so you create one for each control you want to validate. Clicking on save will not allow you to move forward if the field is not filled.

<asp:TextBox runat="server" ID="txt"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" InitialValue="" ControlToValidate="txt" ErrorMessage="Campo requerido" EnableClientScript="true" Text="(*)" />

Then in the code you only call

 if (Page.IsValid)
 {
   // guardar
 }

Well if you want pure javascript, you can use a function to call all the elements with the same css tag. and you check them by category. (All textbox etc ..) So you do not have to mortify yourself for each one.

 function validateForm() {
  var isValid = true;
  $('.txtform').each(function() {
    if ( $(this).val() === '' )
        isValid = false;
  });
  return isValid;
}
  

link

    
answered by 09.01.2019 в 00:18