简体   繁体   English

如果使用required属性指定,则验证HTML表单字段

[英]Validate HTML form fields if it is specified with required attribute

I created a JSP page and I have many forms each in different tabs. 我创建了一个JSP页面,我在不同的选项卡中有很多表单。 So I have added a single submit button common to all forms(So the button is outside of the < form > tag). 所以我添加了所有表单通用的单个提交按钮(因此按钮位于< form >标签之外)。 On each tab, when the submit is clicked, the appropriate forms are being submitted using JQuery. 在每个选项卡上,单击提交时,将使用JQuery提交相应的表单。 In all forms some form fields are required. 在所有形式中,都需要一些表单字段。 And I have specified those fields with the required attribute like the following 我已经使用如下所示的必需属性指定了这些字段

<div class="control-group">
        <label class="control-label input-label" for="hostname">Host :
                    <span class="requiredField"> * </span>
            </label>
        <div class="controls">
            <input type="text" class="inputstyle" name="hostname" placeholder="host" required="required" />
</div>

The problem is when I click on submit button, it does not validate fields which are required. 问题是,当我单击“提交”按钮时,它不会验证所需的字段。 If the submit button is inside the form, it's working. 如果提交按钮在表单内,则表明它正在工作。 But I need common submit button. 但我需要常用的提交按钮。 How to solve this? 怎么解决这个?

I am just thinking in JQuery I am submitting form with form action value. 我只是想在JQuery中提交表单动作值的表单。 So before submitting is it possible to call function to validate form by passing form ID and evaluate the required fields? 那么在提交之前是否可以通过传递表单ID来调用函数来验证表单并评估所需的字段? If so, please help me to code. 如果是这样,请帮我编码。

Thanks 谢谢

UPDATE 1 更新1

<button type="submit" id="submitbtn" class="btn btn-primary inputstyle" onclick="submitForm();">SUBMIT</button>

JQuery for this JQuery为此

function submitForm() {
            var $submitform=$('#formId').val();

            //validateForm($submitform); // I have not created this function.
            $('#'+$submitform).submit();
    }

Assume you have 2 forms (form1 and form 2) to submit on button click... you can call the following function on button click event. 假设你有两个表单(form1和表单2)按钮点击提交...你可以在按钮点击事件上调用以下功能。

function SubmitAllForms()
{
    document.forms.form1.submit();
    document.forms.form2.submit();
}

I think that below code will help you to solve your issue 我认为以下代码将帮助您解决您的问题

HTML HTML

   <form action="insertserverdata.php" id="myForm">
        <input type="text" name="userName">
         <input type="text" name="userPass">
        <input type="submit">
      </form>

JS JS

 var formRules={userName:{required:true},userPass:{required:true}};

 $("#myForm").validate({rules:formRules});

 $("#myForm").submit(function(event){

 if(! $("#myForm").valid()){

   return;

 }

 });


//Also you can get your form fields by using below code

  var values = {};
  $.each($('#myForm').serializeArray(), function(i, field) {
     values[field.name] = field.value;
  });          

ASSUMPTION: you click on tab, okay thats great you could create a hidden input and change it's value based on the tab you pressed lets illustrate more: you have form1,form2 and form3 on three tabs to toggle between so when you click on specific tab lets say tab1 which leads to form1 onclick you need to call method setVariable "which I made up" this method sets the value of your hidden input to let's say 1, example: 假设:你单击选项卡,好吧,你可以创建一个隐藏的输入并根据你按下的选项卡改变它的值让我们说明更多:你有三个选项卡上的form1,form2和form3来切换,所以当你点击特定的选项卡让我们说tab1导致form1 onclick你需要调用方法setVariable“我编造了”这个方法设置隐藏输入的值让我们说1,例如:

<div id="tab1" onclick="setVariable(1)">

now in you js you have this method: 现在在你js你有这个方法:

function setVariable (value){
    document.getElementById('our hiddin input id').value= value;
}

now what? 怎么办? okay now it's time to validate onclick of your submit button you should call the method validateMyForm but which form?? 好的,现在是时候验证你的提交按钮的onclick你应该调用方法validateMyForm但是哪种形式? well the form that have the same number as your hidden field watch that: 以及与您的隐藏字段具有相同编号的表单:

<input type="submit" onclick="validateMyForm(document.getElementById('hidden input').value)"/>

then in your js: 然后在你的js:

function validateMyForm(val){
    //use a switch or if-else to know which form you're validating and also which action should be submitted
}

that's pretty much the Idea goodluck 这几乎就是Idea goodluck

You can validate your data using client or server side scripts. 您可以使用客户端或服务器端脚本验证数据。 You have asked for a javascript solution here, which is valid. 你在这里要求一个javascript解决方案,这是有效的。 As the javascript will prevent anything from being submitted unless the data is valid. 因为除非数据有效,否则javascript将阻止提交任何内容。

You need a switch or if statement to choose which form to submit. 您需要switch或if语句来选择要提交的表单。 You'll need to have an identifier and this is algorithm: 你需要有一个标识符,这是算法:

AS you are using a form ID You only have to validate a form if you require certain fields completed. 当您使用表单ID时如果需要完成某些字段,您只需验证表单。 getElementByID for the form id is perfect, use the if or switch to choose which form is to be validated and then submitted 表单id的getElementByID是完美的,使用if或switch选择要验证的表单然后提交

eg if id 'lname1' (for form1) is not nothing then and use the javascript function validate() to check all fields of THAT form are filled. 例如,如果id'lname1'(对于form1)并不是什么,那么使用javascript函数validate()来检查该表单的所有字段是否已填充。 You will then have to have error checks, if more than one form has been filled, of once one field in a form has input, the other forms are disabled. 然后,如果已填写多个表单,则必须进行错误检查,一旦表单中的一个字段输入,其他表单将被禁用。

You could also run the if statement- on whether or not the form has been disabled. 您还可以运行if语句,以确定表单是否已被禁用。

To tell you the truth, it would probably be easier and chance for less errors to have a submit button for each for,. 说实话,为每个人提供一个提交按钮可能更容易,也更容易减少错误。

example names: 示例名称:

function Validate()
        {


        // create array containing textbox elements
        var inputs = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email'), document.getElementById('messagetxt')];

        var error;

        for(var i = 0; i<inputs.length; i++)
        // loop through each element to see if value is empty
        {
            if(inputs[i].value == '')
            {
                error = 'Please complete all fields.';
                alert(error);
                return false;
                }
        }
     }


     <form onsubmit="return Validate();"  action="contact.php" method="post" name="contact1" id="contact1"  >


        <input class="input" type="text" placeholder="First Name" name="fname" id="fname" />


        <input class="input" type="text" placeholder="Last Name" name="lname" id="lname"/>

        <input class="input" type="email" placeholder="Email Address" name="email"  id="email"/>

      <textarea placeholder="Message" name="messagetxt" id="messagetxt"></textarea>

    </form>  

     <form onsubmit="return Validate();"  action="contact.php" method="post" name="contact2" id="contact2" >
 //insert form details

    </form>  

        <input type="submit" value="submit" name="submit"  />

See this fiddle: 看到这个小提琴:

http://jsfiddle.net/yvytty/b3qdN/ http://jsfiddle.net/yvytty/b3qdN/

If you need more feedback or clarity pls ask. 如果您需要更多反馈或清晰请求。

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

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