簡體   English   中英

必需的屬性在Safari瀏覽器中不起作用

[英]Required Attribute Not work in Safari Browser

我已嘗試使用以下代碼來使必填字段通知必填字段,但在Safari瀏覽器中無法正常工作。 碼:

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

上面的代碼在firefox中工作。 http://jsfiddle.net/X8UXQ/179/

您可以讓我知道JavaScript代碼或任何workarround嗎? 是javascript新功能

謝謝

Safari(自2017年3月26日起最新版本10.1)不支持此屬性,您需要使用JavaScript。

該頁面包含一個hacky解決方案,該解決方案應添加所需的功能: http : //www.html5rocks.com/zh-CN/tutorials/forms/constraintvalidation/#toc-safari

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:

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

您可以用不太丑陋的警告代替警報,例如顯示帶錯誤消息的DIV:

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

在CSS中:

.hidden {
    display: none;
}

並在HTML中:

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

這種方法的唯一缺點是它無法處理需要填寫的確切輸入。 它將需要一個遍歷表單中所有輸入的循環並檢查值(更好的是,檢查“必需”屬性的存在)。

循環看起來像這樣:

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

如果您使用jQuery,則下面的代碼會更好。 只需將這段代碼放在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;
});

此代碼適用於不支持必填(html5)屬性的瀏覽器

有一個愉快的編碼天的朋友。

我在Safari中遇到了同樣的問題,我只能請大家看看Webshim

我找到了解決方案,這個問題,並為這個一個非常非常有用的,但如果你想以“模擬” Safari的原生HTML5輸入驗證,Webshim為您節省大量的時間。

Webshim為Safari提供了一些“升級”,並幫助它處理HMTL5 datepicker或表單驗證之類的事情。 它不僅易於實現,而且看起來足夠好,可以立即使用它。

同樣在如此有用的答案初始設置為webshim 這里 鏈接帖子的副本:

目前,Safari不支持“必需”輸入屬性。 http://caniuse.com/#search=必需

要在Safari上使用“ required”屬性,可以使用“ webshim”

1-下載webshim

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>

我已經在@Roni的基礎上構建了一個解決方案。

Webshim似乎已棄用,因為它與jquery 3.0不兼容。

重要的是要了解Safari確實會驗證所需的屬性。 不同之處在於它的用途。 與其阻止提交,並在輸入旁邊顯示錯誤消息工具提示,不如讓表單繼續進行。

就是說,checkValidity()是在Safari中實現的,如果未滿足要求的文件,確實會向我們返回false。

因此,為了“修復它”並以最少的干預(沒有額外的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
}

我找到了一個很棒的博客條目,其中包含解決此問題的方法。 與這里的其他建議相比,它以我更滿意的方式解決了問題,並提供了更好的用戶體驗。 它將更改字段的背景顏色以表示輸入是否有效。

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:

$(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';
}

圖片來源: http//blueashes.com/2013/web-development/html5-form-validation-fallback/

(注意:我確實將CSS從帖子擴展到了textarea並選擇了字段)

我使用此解決方案,效果很好

$('#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();
    }
});

2017年3月26日發布的新Safari 10.1現在支持“ required”屬性。

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

您可以將此事件處理程序添加到表單中:

// 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);

在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