简体   繁体   English

防止 html 表单根据输入值提交

[英]Prevent html form submit according to input value

I have a form with bootstrap and Google Apps Script.我有一个带有引导程序和 Google Apps 脚本的表单。 I need to configure a specific validation for a field.我需要为一个字段配置一个特定的验证。 If the input field with the id "estado" has the value 1, the form should not be submitted.如果 ID 为“estado”的输入字段的值为 1,则不应提交表单。 The value of the input field is generated by a google app script function and its updated when the input field "inputid" change.输入字段的值由谷歌应用程序脚本 function 生成,并在输入字段“inputid”更改时更新。

This is my code:这是我的代码:

<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" onchange="onchangeestado()" required>
        <div class="invalid-feedback">
            No ha ingresado un identificador de viaje.
        </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">
            El viaje señalado ya se encuentra cerrado.
        </div>
    </div> 
</div>
<div class="form-row">
    <div class="form-group col-md-6">
        <label for="kminicial">Kilometraje Final</label>
        <input type="number" class="form-control" id="kmfinal" required>
        <div class="invalid-feedback">
            No ha ingresado el kilometraje inicial del vehículo.
        </div>
    </div>
</div> 
<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#modal" onclick="verifyError()">Enviar datos</button>
<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> 
<script>
    var arrayOfValues;
    function verifyError() {
        var estado = document.getElementById("estado");
        var inputid = document.getElementById("inputid");
        if(estado == 1) {
            inputid.classList.add("is-invalid");
        }
        else{
  document.getElementById("enviar").addEventListener("click",afterButtonClicked);
        }
    }  
    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("loading").remove();
</script>

When i submit the form, the form is sent in the same way and register the values on my spreadsheet when the value is equal to "1".当我提交表单时,表单以相同的方式发送并在值等于“1”时在我的电子表格上注册值。 Can you help me with this problem?你能帮我解决这个问题吗? Greetings!问候!

I'm not sure what number you require to be present for the form validation, obviously not the number 1. So, you might try this:我不确定您需要为表单验证提供什么数字,显然不是数字 1。所以,您可以试试这个:

<input type="text" class="form-control" id="estado" onkeypress='validate(event)' required disabled>

Here's the javascript.这是 javascript。

function validate(evt) {
  var theEvent = evt || window.event;

  // Handle paste
  if (theEvent.type === 'paste') {
      key = event.clipboardData.getData('text/plain');
  } else {
  // Handle key press
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode(key);
  }
  var regex = /[2-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

Not sure if this will work for you, you may have to play around with the number parameters in the "var regex" to get it to work on your page.不确定这是否适合您,您可能必须使用“var regex”中的数字参数才能使其在您的页面上工作。 This also prevents the user from putting in wrong data, or trying to do a copy/paste into the field.这也可以防止用户输入错误的数据,或尝试复制/粘贴到字段中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM