简体   繁体   English

HTML5表单验证的Javascript代码不起作用

[英]Javascript Code For HTML5 Form Validation Not Working

I'm new to JavaScript so I have no idea why this code does not work and validate my HTML5 Form like it should. 我是JavaScript的新手,所以我不知道为什么该代码无法正常工作,并按应有的方式验证我的HTML5表单。

The JavaScript code which can be found below is supposed to check if the browser supports the required attribute and if it doesn't then it will validate the form and check for any empty spaces. 可以在下面找到的JavaScript代码应该检查浏览器是否支持required属性,如果不支持,则它将验证表单并检查是否有空白。

I got the code from this website . 我从这个网站上得到了代码。

In the body of the webpage containing my form I have this: 在包含我的表单的网页正文中,我有以下内容:

Below is the contactvalidate.js file: 以下是contactvalidate.js文件:

$('#formTemplate').submit(function() {
if (!attributeSupported("required") || ($.browser.safari)) {
  $("#formTemplate [required]").each(function(index) {
  if (!$(this).val()) {
     alert("Please fill all required fields.");
     return false;
    }
   });
  }
 return false;
});

Do I need to change anything in this code or should it work? 我需要更改此代码中的任何内容还是应该工作?

As I've said I'm new to JavaScript so any help you guys could give me is greatly appreciated. 就像我说过的,我是JavaScript的新手,非常感谢你们能给我的任何帮助。

EDIT : 编辑:

Here is my updated code: 这是我更新的代码:

$(function(){
        $('#contactForm').submit(function() {
            if (!attributeSupported("required") || ($.browser.safari)) {
                   $("#contactForm [required]").each(function(index) {
                         if (!$(this).val()) {
                               alert("Please Fill In All Required Fields.");
                               return false;
                         }
                   });
            }
  return false;
        });
    });


    function attributeSupported(attribute) {
        return (attribute in document.createElement("input"));
    }

The problem I am having is: When any field is empty it comes up with an alert (This is fine) but when the fields are filled in, the submit button doesn't work. 我遇到的问题是:当任何字段为空时,它会发出警报(这很好),但是当字段被填写时,提交按钮将不起作用。

I have tried changing the second return false; 我尝试将第二个 return false;更改为return false; to return true; return true; but that comes up with alert as expected but then sends the form through anyway! 但这会带来预期的警报,但是无论如何都会发送表单!

EDIT 2: 编辑2:

Here is my HTML5 Form code: 这是我的HTML5表单代码:

<form id="contactForm" method="post" action="php/contactform.php">

  <label>Name:</label>
  <input name="name" type="text" pattern="[a-zA-Z. -]+" placeholder="Your Name" title="You can only use letters in this box" required="required" data-required="true" autofocus="autofocus" />

  <label>Contact Number:</label>
  <input name="phone" type="tel" pattern="[0-9. -]+" placeholder="Your Contact Number" title="You can only use numerical values in this box" required="required" data-required="true" maxlength="13" />

  <label>Email:</label>
  <input name="email" type="email" placeholder="me@example.com" required="required" data-required="true"/>

  <label>Type Of Enquiry:</label>
  <input name="enquirytype" type="text" placeholder="Enquiry Type" required="required" data-required="true" maxlength="20" />

  <label>Message:</label>
  <textarea name="message" placeholder="Your Message" required="required" data-required="true"></textarea>

                <br />
                <br />

  <input id="submit" name="submit" type="submit" value="Submit" />
</form>

EDIT 3: 编辑3:

The reason it is not working is because Safari 'thinks' it has the required attribute that is why I was checking the browser rather than the attribute. 它不起作用的原因是因为Safari认为它具有required属性,这就是为什么我要检查浏览器而不是该属性的原因。

Could you adapt the code to check the browser rather than the attribute? 您能否修改代码以检查浏览器而不是属性?

Also do I need this in my <head> tag: 我也需要在我的<head>标记中这样做吗:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

I put it in but wasn't sure if I need it! 我放进去了,但不确定是否需要!

EDIT 4: 编辑4:

Right, when I press submit it comes up with the alert and as soon as I press Ok or press the 'x' button it sends the form through anyway with it being blank. 正确,当我按下“提交”时,它会出现alert并且当我按下“ Ok或按下“ x”按钮时,它将以空白形式发送表单。

Also could you explain why you have mentioned Chrome in the code below? 还可以解释一下为什么在下面的代码中提到了Chrome吗?

Here is the code that I'm using: 这是我正在使用的代码:

//Function Declaration

function attributeSupported(attribute) {
    return (attribute in document.createElement("input"));
}

function isSafariOnly() {
    return navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
}

//Main Code

$(function () {
    $('#contactForm').submit(function () {
        if (!attributeSupported("required") || isSafariOnly()) {
            $("#contactForm [required]").each(function (index) {
                if (!$(this).val()) {
                    alert("Please Fill In All Required Fields.");
                    return false;
                }
            });
        }
        return true;
    });
});

EDIT 5: 编辑5:

Take a look at the JSFiddle 看看JSFiddle

Even when it is opened in Safari it DOESN'T work. 即使当它打开Safari 工作。

When I press submit it comes up with the alert and as soon as I press Ok or press the 'x' button it sends the form through anyway with it being blank. 当我按下“ submit它会出现alert并且当我按下“ Ok或按下“ x”按钮时,它将以空白形式发送表单。

Please can you provide a fix for this? 请您提供解决方法吗?

Like Ethan Brown said, you might missing attributeSupported function. 就像Ethan Brown所说的那样,您可能会缺少attributeSupported函数。 If this is the case, you can add it to your code. 在这种情况下,可以将其添加到代码中。 It will check if attribute (in your case it's "required") is supported 它将检查是否支持属性(在您的情况下为“必需”)

function attributeSupported(attribute) {
    return (attribute in document.createElement("input"));
}

EDIT: 编辑:

After you provided HTML code and more information about your issue I was able to create working example for you at JSFiddle . 在您提供HTML代码和有关您的问题的更多信息之后,我能够在JSFiddle为您创建工作示例。 The problem you had with $.browser.safari your javascript code was braiking on this statement. 您在$ .browser.safari中遇到的问题是您的JavaScript代码在此语句上不受欢迎。 After checking documentation I found that it was deprecated in jQuery 1.9, and it is recommended to use feature detection instead of browser detection. 检查文档后,我发现它在jQuery 1.9中已被弃用,建议使用功能检测而不是浏览器检测。 I added isSafari function for you and used that function instead of jQuery browser detection. 我为您添加了isSafari函数,并使用该函数代替了jQuery浏览器检测。

function isSafariOnly() {
    return navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
}

So your main JavaScript code now looks like 因此,您的主要JavaScript代码现在看起来像

$(function () {
    $('#contactForm').submit(function () {
        if (!attributeSupported("required") || isSafariOnly()) {
            $("#contactForm [required]").each(function (index) {
                if (!$(this).val()) {
                    alert("Please Fill In All Required Fields.");
                    return false;
                }
            });
        }
        return true;
    });
});

remember if you return false from your function, your form will not be submitted, that is why you have first return false when your form failed validation and you don't want to submit your form. 请记住,如果您从函数中返回false,则将不提交表单,这就是为什么当表单验证失败且您不想提交表单时,首先return false原因。 When your form passed validation and everything is fine, you return true and your form will now be submitted to the url provided in action of the form tag. 当您的表单通过验证并且一切都很好时,您将return true并且您的表单现在将被提交到form标记提供的url中。

Please notice in my jsFiddle example I have google address. 请注意,在我的jsFiddle示例中,我有Google地址。 In your example you will have to specify your page address. 在您的示例中,您将必须指定您的页面地址。

EDIT 2: 编辑2:

 Also do I need this in my <head> tag: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> 

Yes, you need it. 是的,您需要它。 That is a reference to your jQuery library (everywhere you see $ in your code is a jQuery). 那是对jQuery库的引用(在代码中看到$的每个地方都是jQuery)。 However I would not recommend to use jquery-latest in production, because if there is some break change, your code will stop working on production. 但是,我不建议在生产环境中使用jquery-latest,因为如果发生一些中断更改,您的代码将停止在生产环境中工作。 Instead I would recommend to use well known and tested version. 相反,我建议使用众所周知且经过测试的版本。 For instance 例如

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Please notice you have to have <script ...></script> otherwise it will not work. 请注意,您必须具有<script ...></script>否则它将不起作用。

Could you adapt the code to check the browser rather than the attribute? 您能否修改代码以检查浏览器而不是属性?

If you need to check only for Safari browser just use: 如果您只需要检查Safari浏览器,请使用:

if (isSafariOnly()) {
    $("#contactForm [required]").each(function (index) {
        if (!$(this).val()) {
            alert("Please Fill In All Required Fields.");
            return false;
         }
    });
}

EDIT 3: 编辑3:

Also could you explain why you have mentioned Chrome in the code below? 还可以解释一下为什么在下面的代码中提到了Chrome吗?

The reason for that is because Chrome browser has both 'Chrome' and 'Safari' inside of userAgent, however Safari browser has 'Safari' only. 原因是因为Chrome浏览器在userAgent中同时具有“ Chrome”和“ Safari”,但是Safari浏览器仅具有“ Safari”。 In your case you want to identify 'Safari' browser only. 在您的情况下,您只想识别“ Safari”浏览器。 In order to do that I needed to check userAgent for 'Safari' but exclude 'Chrome', this way it will guarantee Safari browsers only. 为此,我需要检查userAgent中的“ Safari”,但不包括“ Chrome”,这样就可以保证仅Safari浏览器。

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

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