简体   繁体   English

必需的属性在Safari浏览器中不起作用

[英]Required Attribute Not work in Safari Browser

I have tried following code for make the required field to notify the required field but its not working in safari browser. 我已尝试使用以下代码来使必填字段通知必填字段,但在Safari浏览器中无法正常工作。 Code: 码:

 <form action="" method="POST">
        <input  required />Your name:
        <br />
        <input type="submit" />
    </form>

Above the code work in firefox. 上面的代码在firefox中工作。 http://jsfiddle.net/X8UXQ/179/ http://jsfiddle.net/X8UXQ/179/

Can you let me know the javascript code or any workarround? 您可以让我知道JavaScript代码或任何workarround吗? am new in javascript 是javascript新功能

Thanks 谢谢

Safari, up to version 10.1 from Mar 26, 2017, doesn't support this attribute, you need to use JavaScript. Safari(自2017年3月26日起最新版本10.1)不支持此属性,您需要使用JavaScript。

This page contains a hacky solution, that should add the desired functionality: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari 该页面包含一个hacky解决方案,该解决方案应添加所需的功能: http : //www.html5rocks.com/zh-CN/tutorials/forms/constraintvalidation/#toc-safari

HTML: HTML:

<form action="" method="post" id="formID">
    <label>Your name: <input required></label><br>
    <label>Your age: <input required></label><br>
    <input type="submit">
</form>

JavaScript: JavaScript:

var form = document.getElementById('formID'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
        if (!event.target.checkValidity()) {
            event.preventDefault(); // dismiss the default functionality
            alert('Please, fill the form'); // error message
        }
    }, false);

You can replace the alert with some kind of less ugly warning, like show a DIV with error message: 您可以用不太丑陋的警告代替警报,例如显示带错误消息的DIV:

document.getElementById('errorMessageDiv').classList.remove("hidden");

and in CSS: 在CSS中:

.hidden {
    display: none;
}

and in HTML: 并在HTML中:

<div id="errorMessageDiv" class="hidden">Please, fill the form.</div>

The only drawback to this approach is it doesn't handle the exact input that needs to be filled. 这种方法的唯一缺点是它无法处理需要填写的确切输入。 It would require a loop accross all inputs in the form and checking the value (and better, check for "required" attribute presence). 它将需要一个遍历表单中所有输入的循环并检查值(更好的是,检查“必需”属性的存在)。

The loop may look like this: 循环看起来像这样:

var elems = form.querySelectorAll("input,textarea,select");
for (var i = 0; i < elems.length; i++) {
    if (elems[i].required && elems[i].value.length === 0) {
        alert('Please, fill the form'); // error message
        break; // show error message only once
    }
}

If you go with jQuery then below code is much better. 如果您使用jQuery,则下面的代码会更好。 Just put this code bottom of the jquery.min.js file and it works for each and every form. 只需将这段代码放在jquery.min.js文件的底部即可,它适用于每种形式。

Just put this code on your common .js file and embed after this file jquery.js or jquery.min.js 只需将这段代码放在您的通用.js文件中,然后嵌入到该文件jquery.js或jquery.min.js之后

$("form").submit(function(e) {

    var ref = $(this).find("[required]");

    $(ref).each(function(){
        if ( $(this).val() == '' )
        {
            alert("Required field should not be blank.");

            $(this).focus();

            e.preventDefault();
            return false;
        }
    });  return true;
});

This code work with those browser which does not support required (html5) attribute 此代码适用于不支持必填(html5)属性的浏览器

Have a nice coding day friends. 有一个愉快的编码天的朋友。

I had the same problem with Safari and I can only beg you all to take a look at Webshim ! 我在Safari中遇到了同样的问题,我只能请大家看看Webshim

I found the solutions for this question and for this one very very useful, but if you want to "simulate" the native HTML5 input validation for Safari, Webshim saves you a lot of time. 我找到了解决方案,这个问题,并为这个一个非常非常有用的,但如果你想以“模拟” Safari的原生HTML5输入验证,Webshim为您节省大量的时间。

Webshim delivers some "upgrades" for Safari and helps it to handle things like the HMTL5 datepicker or the form validation. Webshim为Safari提供了一些“升级”,并帮助它处理HMTL5 datepicker或表单验证之类的事情。 It's not just easy to implement but also looks good enough to just use it right away. 它不仅易于实现,而且看起来足够好,可以立即使用它。

Also useful answer on SO for initial set up for webshim here ! 同样在如此有用的答案初始设置为webshim 这里 Copy of the linked post: 链接帖子的副本:

At this time, Safari doesn't support the "required" input attribute. 目前,Safari不支持“必需”输入属性。 http://caniuse.com/#search=required http://caniuse.com/#search=必需

To use the 'required' attribute on Safari, You can use 'webshim' 要在Safari上使用“ required”属性,可以使用“ webshim”

1 - Download webshim 1-下载webshim

2 - Put this code : 2-输入以下代码:

<head>
    <script src="js/jquery.js"></script>
    <script src="js-webshim/minified/polyfiller.js"></script>
    <script> 
        webshim.activeLang('en');
        webshims.polyfill('forms');
        webshims.cfg.no$Switch = true;
    </script>
</head>

I have built a solution on top of @Roni 's one. 我已经在@Roni的基础上构建了一个解决方案。

It seems Webshim is deprecating as it won't be compatible with jquery 3.0. Webshim似乎已弃用,因为它与jquery 3.0不兼容。

It is important to understand that Safari does validate the required attribute. 重要的是要了解Safari确实会验证所需的属性。 The difference is what it does with it. 不同之处在于它的用途。 Instead of blocking the submission and show up an error message tooltip next to the input, it simply let the form flow continues. 与其阻止提交,并在输入旁边显示错误消息工具提示,不如让表单继续进行。

That being said, the checkValidity() is implemented in Safari and does returns us false if a required filed is not fulfilled. 就是说,checkValidity()是在Safari中实现的,如果未满足要求的文件,确实会向我们返回false。

So, in order to "fix it" and also show an error message with minimal intervention (no extra Div's for holding error messages) and no extra library (except jQuery, but I am sure it can be done in plain javascript)., I got this little hack using the placeholder to show standard error messages. 因此,为了“修复它”并以最少的干预(没有额外的Div用于保存错误消息)和没有额外的库(jQuery除外,但我敢肯定,可以用普通的javascript完成)显示错误消息。使用占位符显示标准错误消息的小技巧。

$("form").submit(function(e) {

  if (!e.target.checkValidity()) {
    console.log("I am Safari"); // Safari continues with form regardless of checkValidity being false
    e.preventDefault(); // dismiss the default functionality

    $('#yourFormId :input:visible[required="required"]').each(function () {
      if (!this.validity.valid) {
        $(this).focus();
        $(this).attr("placeholder", this.validationMessage).addClass('placeholderError');
        $(this).val(''); // clear value so it shows error message on Placeholder.
        return false;
      }
    });
    return; // its invalid, don't continue with submission
  }

  e.preventDefault(); // have to add it again as Chrome, Firefox will never see above
}

I found a great blog entry with a solution to this problem. 我找到了一个很棒的博客条目,其中包含解决此问题的方法。 It solves it in a way that I am more comfortable with and gives a better user experience than the other suggestions here. 与这里的其他建议相比,它以我更满意的方式解决了问题,并提供了更好的用户体验。 It will change the background color of the fields to denote if the input is valid or not. 它将更改字段的背景颜色以表示输入是否有效。

CSS: CSS:

/* .invalid class prevents CSS from automatically applying */
.invalid input:required:invalid {
    background: #BE4C54;
}
.invalid textarea:required:invalid {
    background: #BE4C54;
}
.invalid select:required:invalid {
    background: #BE4C54;
}
/* Mark valid inputs during .invalid state */
.invalid input:required:valid {
    background: #17D654 ;
}
.invalid textarea:required:valid {
    background: #17D654 ;
}
.invalid select:required:valid {
    background: #17D654 ;
}

JS: JS:

$(function () {
    if (hasHtml5Validation()) {
        $('.validate-form').submit(function (e) {
            if (!this.checkValidity()) {
                // Prevent default stops form from firing
                e.preventDefault();
                $(this).addClass('invalid');
                $('#status').html('invalid');
            }
            else {
                $(this).removeClass('invalid');
                $('#status').html('submitted');
            }
        });
    }
});

function hasHtml5Validation () {
    return typeof document.createElement('input').checkValidity === 'function';
}

Credit: http://blueashes.com/2013/web-development/html5-form-validation-fallback/ 图片来源: http//blueashes.com/2013/web-development/html5-form-validation-fallback/

(Note: I did extend the CSS from the post to cover textarea and select fields) (注意:我确实将CSS从帖子扩展到了textarea并选择了字段)

I use this solution and works fine 我使用此解决方案,效果很好

$('#idForm').click(function(e) {
    e.preventDefault();
    var sendModalForm = true;
    $('[required]').each(function() {
        if ($(this).val() == '') {
            sendModalForm = false;
            alert("Required field should not be blank."); // or $('.error-message').show();
        }
    });

    if (sendModalForm) {
        $('#idForm').submit();
    }
});

The new Safari 10.1 released Mar 26, 2017, now supports the "required" attribute. 2017年3月26日发布的新Safari 10.1现在支持“ required”属性。

http://caniuse.com/#search=required http://caniuse.com/#search=必需

You can add this event handler to your form: 您可以将此事件处理程序添加到表单中:

// Chrome and Firefox will not submit invalid forms
// so this code is for other browsers only (e.g. Safari). 
form.addEventListener('submit', function(event) {
    if (!event.target.checkValidity()) {
        event.preventDefault();
        var inputFields = form.querySelectorAll('input');
        for (i=0; i < inputFields.length; i++) {
            if (!inputFields[i].validity.valid) {
                inputFields[i].focus(); // set cursor to first invalid input field
                return false;
            }
        }
    }
}, false);

Within each() function I found all DOM element of text input in the old version of PC Safari, I think this code useful for newer versions on MAC using inputobj['prpertyname'] object to get all properties and values: 在each()函数中,我发现PC Safari的旧版本中所有文本输入的DOM元素,我认为这段代码对于MAC上的新版本非常有用,它使用inputobj ['prpertyname']对象获取所有属性和值:

    $('form').find("[required]").each(function(index, inputobj) {
        if (inputobj['required'] == true) { // check all required fields within the form
            currentValue = $(this).val();
            if (currentValue.length == 0) {
                // $.each((inputobj), function(input, obj) { alert(input + ' - ' + obj); }); // uncomment this row to alert names and values of DOM object
                var currentName = inputobj['placeholder']; // use for alerts
                return false // here is an empty input
            }
        }
    });
function customValidate(){
    var flag=true;
    var fields = $('#frm-add').find('[required]');  //get required field by form_ID

    for (var i=0; i< fields.length;i++){
      debugger
      if ($(fields[i]).val()==''){
        flag = false;
        $(fields[i]).focus();
      }
    }
    return flag;
  }


if (customValidate()){
// do yor work
 }

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

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