简体   繁体   English

使用 javascript/jquery 验证动态 php 表单

[英]Validate dynamic php form with javascript/jquery

I've tried the following code for javascript validation.我已尝试使用以下代码进行 javascript 验证。 When the form is submitted, only the first input field is validated.提交表单时,仅验证第一个输入字段。 How could I validate all the dynamic values of the form?如何验证表单的所有动态值?

<script type="text/javascript">
            function validate() {
                if (document.f.phone.value.length == "0") {
                    alert("Phone is required");
                    document.f.phone.focus();
                    return false;
                } else if (document.f.file.value.length == "0") {
                    alert("file is required ");
                    document.f.file.focus();
                    return false;
                } 
                
                return true;
            }   
        </script>

<?php

    echo '<form name="f" action="" method="post" enctype="multipart/form-data" onsubmit="return validate();">
           <input type="text" name="phone[]" class="required">
           <input type="file" name="file[]" class="required">
           
           <input type="button" class="add" value="add"/>
           <input type="submit" value="Submit" name="submit" class="Submit">    
    ';
    
?>

if i understood correctly then you want to validate dynamic value in the form.如果我理解正确,那么您想验证表单中的动态值。 instead of writing logic to validate the fields just add the required keyword to the fields which you want to make mandatory.而不是编写逻辑来验证字段,只需将required关键字添加到您想要强制的字段中。 that should save you extra effort of writing validation.这应该可以节省您编写验证的额外工作。 go for custom validation when inbuilt validation are not enough当内置验证不够时进行自定义验证

 <form name="f" action="" method="post" enctype="multipart/form-data"> <input type="text" name="phone[]" required class="required"> <input type="file" name="file[]" required class="required"> <input type="button" class="add" value="add" /> <input type="submit" value="Submit" name="submit" class="Submit">

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

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