Don't submit the form if input field value is equal to a specific text

折月煮酒 提交于 2021-02-11 17:15:29

问题


I have a form with bootstrap and Google Apps Script. I have defined a general validation for the form, but now I need to configure a specific validation for a field. If the input field with the id "estado" has the value "Terminado", the form should not be submitted. The value of the input field is generated by a google app script function and its updated when the input field "inputid" change.

The input fields estado is determined by the value on "inputid". When i change the value of inputid My script go to a DB and get the value of estado like a vlookup from excel. Then, When i change inputid My code search or lookup for the value on the column estado of the Data Base.

This is my code:

<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>Formulario Llegada</title>
  <?!=include("userformarrive-css");?>    
  </head>
  <body>
  
  <h4 align="center">Formulario de llegada</h4>
  
  <div class ="container">
   <form id = "userform">

<div class="form-row">
  <div class="form-group col-md-6">
    <label for="inputid">Identificador de viaje</label>
    <input type="text" class="form-control" id="inputid" required>
    <div class="invalid-feedback">
      No ha ingresado los datos o el viaje señalado ya se encuentra cerrado.
    </div>
  </div>
  <div class="form-group col-md-6">
    <label for="estado">Estado</label>
    <input type="text" class="form-control" id="estado" required disabled>
    <div class="invalid-feedback">
      No ha ingresado los datos o estos no son válidos.
    </div>
  </div>
</div>
       <button class="btn btn-primary" type="button" data-toggle="modal" data-target="#modal">Enviar datos</button>

    
  
  </div>
  </form>
  
  
  <!-- Acá van las notificaciones -->
  
  <div id="notifications">
  
  <div id="errornotification" class="toast" style="position: absolute; top: 0; right: 0;" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
  <div class="toast-header">
    <strong class="mr-auto">Error</strong>
    <small>Notificación</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    Uno o más campos requeridos no han sido completados dentro del formulario
  </div>
</div>
  
   <div id="successnotification"  class="toast" style="position: absolute; top: 0; right: 0;" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
  <div class="toast-header">
    <strong class="mr-auto">Datos correctos</strong>
    <small>Notificación</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    El formulario ha sido enviado de forma correcta. Recibirá un correo con el número de la operación ID para luego cerrar la llegada.
  </div>
</div>
    
  </div>
 
      <div id="loading" class="loading pt-40">
         <div class="d-flex justify-content-center">
         <div>
        
        <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;"role="status">
        <span class="sr-only">Cargando</span>
        </div>
         <div> Cargando</div>
       </div>
      </div>
     
     </div>
     
<div id="modal" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Envío de Formulario</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>¿Desea enviar el registro?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
        <button class="btn btn-outline-primary" id ="enviar" >Registrar Salida</button>
      </div>
    </div>
  </div>
</div>  




var arrayOfValues;

function afterButtonClicked() {

  if (validate()) {

    var cuenta = document.getElementById("cuenta");
    var inputid = document.getElementById("inputid");
    var estado = document.getElementById("estado");
    var kmfinal = document.getElementById("kmfinal");

    var rowDataarrive = {
      cuenta: cuenta.value,
      inputid: inputid.value,
      estado: estado.value,
      kmfinal: kmfinal.value,
    };

    google.script.run.addNewRowarrive(rowDataarrive);
    $('#modal').modal('hide')
    $('#successnotification').toast('show')
    setTimeout(function () {
      location.reload()
    }, 6000);
  } else {
    $('#modal').modal('hide')
    $('#errornotification').toast('show')
  }
}

function validate() {
  var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
  Array.prototype.forEach.call(fieldsToValidate, function (el) {
    if (el.checkValidity()) {
      el.classList.remove("is-invalid");
    } else {
      el.classList.add("is-invalid");
    }
  });

  return Array.prototype.every.call(fieldsToValidate, function (el) {
    return el.checkValidity();
  });
}

function getId() {
  var idCode = document.getElementById("inputid").value;
  google.script.run.withSuccessHandler(updateIdcode).getId(idCode);
}

function updateIdcode(estadolist) {
  document.getElementById("estado").value = estadolist;
}

google.script.url.getLocation(function (location) {
  document.getElementById("inputid").value =
    location.parameters.inputid[0];
  getId();
});

document.getElementById("inputid").addEventListener("input", getId);
document.getElementById("enviar").addEventListener("click", afterButtonClicked);
document.getElementById("loading").remove();

Now, I tried a lot of ways to configure the specific input's field validation, but nothing worked. I tried to set the value "empty" if the input value had the value "Terminado" with a function and take advantage of my general validation, but it didn't work.
Do you have an idea to solve my problem?


回答1:


Like @Fritzdultimate said you probably need to use event.preventDefault() but I think there is also a problem in your validate function.

function validate() {
  var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
  Array.prototype.forEach.call(fieldsToValidate, function (el) {
    if (el.checkValidity()) {
      el.classList.remove("is-invalid");
    } else {
      el.classList.add("is-invalid");
    }
  });

  return Array.prototype.every.call(fieldsToValidate, function (el) {
    return el.checkValidity();
  });
}

Instead of Array.prototype you should have the actual array you want to run the function on like this:

function validate() {
  var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
  fieldsToValidate.forEach(function (el) {
    if (el.checkValidity()) {
      el.classList.remove("is-invalid");
    } else {
      el.classList.add("is-invalid");
    }
  });

  return fieldsToValidate.every(function (el) {
    return el.checkValidity();
  });
}

Edit: @dwmorrin is correct, fieldsToValidate.forEach(function (el) { is the same as Array.prototype.forEach.call(fieldsToValidate, function (el) { so that shouldn't make a difference.




回答2:


I found the solution calling in first instance the specific validation and if return true, goes to the second validation this is the javascript code:

var arrayOfValues;


function buttonClickAction(){
var isValid = document.getElementById("estado").value
if(isValid == 1){

$('#errornotificationestado').toast('show')
$('#modal').modal('hide')

isValid.classList.add("is-invalid")

}else {

afterButtonClicked()

}
}


function afterButtonClicked(){

if(validates()){


var cuenta = document.getElementById("cuenta");   
var inputid = document.getElementById("inputid");
var estado = document.getElementById("estado");
var kmfinal = document.getElementById("kmfinal");


    
var rowDataarrive = {cuenta: cuenta.value,inputid:inputid.value,
               estado: estado.value,kmfinal:kmfinal.value,
                          
               };
     
             
               
google.script.run.addNewRowarrive(rowDataarrive);
$('#modal').modal('hide')
$('#successnotification').toast('show')
setTimeout(function(){location.reload()}, 6000);
} else{
$('#modal').modal('hide')
$('#errornotification').toast('show')
}
}

function validates(){

var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
Array.prototype.forEach.call(fieldsToValidate, function(el){
if(el.checkValidity()){
el.classList.remove("is-invalid");

}else{
el.classList.add("is-invalid");


}
   
});

return Array.prototype.every.call(fieldsToValidate, function(el){
return el.checkValidity();

});

}
function getId(){

var idCode = document.getElementById("inputid").value;

google.script.run.withSuccessHandler(updateIdcode).getId(idCode);

}

function updateIdcode(estadolist){
document.getElementById("estado").value = estadolist; 

}
 
google.script.url.getLocation(function(location) {
document.getElementById("inputid").value = location.parameters.inputid[0];
getId(); 
});
     
document.getElementById("inputid").addEventListener("input",getId);
document.getElementById("enviar").addEventListener("click",buttonClickAction);
document.getElementById("loading").remove();


来源:https://stackoverflow.com/questions/63291848/dont-submit-the-form-if-input-field-value-is-equal-to-a-specific-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!