【问题标题】:Prevent html form submit according to input value防止根据输入值提交html表单
【发布时间】:2020-11-30 12:24:40
【问题描述】:

我有一个带有引导程序和 Google Apps 脚本的表单。我需要为一个字段配置一个特定的验证。如果 ID 为“estado”的输入字段的值为 1,则不应提交表单。输入字段的值由谷歌应用脚​​本函数生成,并在输入字段“inputid”更改时更新。

这是我的代码:

<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>

当我提交表单时,表单以相同的方式发送并在值等于“1”时在我的电子表格上注册值。 你能帮我解决这个问题吗? 问候!

【问题讨论】:

    标签: javascript forms google-apps-script submit form-submit


    【解决方案1】:

    我不确定您在表单验证时需要提供什么数字,显然不是数字 1。所以,您可以试试这个:

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

    这是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();
      }
    }
    

    不确定这是否适合您,您可能需要使用“var regex”中的数字参数才能使其在您的页面上工作。 这也可以防止用户输入错误的数据,或尝试复制/粘贴到字段中。

    【讨论】:

    • 我有两个参数,1 和 0。当输入值等于 0 时提交,如果值等于 1,则不提交表单。我看不到在哪里传递参数这个功能。抱歉,我对 Javascript 很陌生。你能给我解释一下吗?
    • 啊啊我明白了,在正则表达式中你没有包含数字 1 ajajja 抱歉...我现在试试...
    • 我用代码试过了,但现在无论如何都没有发送表单...
    • @LuisGermánOrregoCampano 请分享你的发现
    • 很高兴您找到了解决方案。请与社区分享。
    猜你喜欢
    • 2016-02-07
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多