javascript jQuery 验证和占位符冲突
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4410118/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validation and Placeholder conflict
提问by WNRosenberg
I'm using the jQuery Validation plugin to validate a form on my site.
我正在使用 jQuery 验证插件来验证我网站上的表单。
http://docs.jquery.com/Plugins/Validation
http://docs.jquery.com/Plugins/Validation
I'm also using the following code to provide Placeholder support for browsers that do not support the HTML5 placeholder=""attribute.
我还使用以下代码为不支持 HTML5placeholder=""属性的浏览器提供占位符支持。
// To detect native support for the HTML5 placeholder attribute
var fakeInput = document.createElement("input"),
    placeHolderSupport = ("placeholder" in fakeInput);
// Applies placeholder attribute behavior in web browsers that don't support it
if (!placeHolderSupport) {
    $('[placeholder]').focus(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function() {
        var input = $(this);
        if (input.val() == '') {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur().parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() { //line 20
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        });
    });
}
When I submit my form, the following things happen:
当我提交表单时,会发生以下情况:
In browsers that support the placeholderattribute, the validate()function fires and everything works like it is supposed to.
在支持该placeholder属性的浏览器中,该validate()函数会触发,一切都按预期运行。
In browsers that do not support the placeholderattribute, lines 20-25 clear all the "placeholders" and then the validate()function fires.  If there are no errors, the page submits and everything works like it is supposed to.
在不支持该placeholder属性的浏览器中,第 20-25 行清除所有“占位符”,然后validate()函数会触发。如果没有错误,页面就会提交,一切都像预期的那样工作。
In unsupported browsers, in the event that there are errors, the appropriate fields get applied class="error"like usual -- but the placeholder text doesn't come back until the blur()event happens on a particular field.  This leaves those fields blank -- and since there's no labels (just the placeholderattribute) users are left to guess at what each empty field is supposed to contain until the blur()event happens.
在不受支持的浏览器中,如果出现错误,则会class="error"像往常一样应用适当的字段——但占位符文本不会返回,直到blur()事件发生在特定字段上。这使得这些字段为空——并且由于没有标签(只有placeholder属性),用户只能猜测每个空字段应该包含什么,直到blur()事件发生。
The other problem that unsupported browsers have is that since the placeholder fix modifies the valueattribute to display the placeholder, fields that are marked as required pass validation when they should be failing.
不受支持的浏览器的另一个问题是,由于占位符修复修改了value属性以显示占位符,标记为必需的字段在应该失败时通过验证。
It seems there's no easy way to use the Validation plugin with the placeholder support code.
似乎没有简单的方法来使用带有占位符支持代码的验证插件。
I'm looking to either modify the placeholder support code or add a submitHandler: {}function as a parameter to the validate()function to get this working in unsupported browsers.
我希望修改占位符支持代码或添加一个submitHandler: {}函数作为函数的参数,以validate()使其在不受支持的浏览器中工作。
回答by dido
I ran into a similar issue. Have you gotten yours to work? I'd love to compare notes.
我遇到了类似的问题。你让你的工作了吗?我很想比较笔记。
FWIW, here's what I did:
FWIW,这就是我所做的:
Add input placeholders to the jQuery support object:
将输入占位符添加到 jQuery 支持对象:
$.support.placeholder = (function() {
    var i = document.createElement( 'input' );
    return 'placeholder' in i;
})();
The placeholder chain:
占位符链:
$('input')
    .addClass('hint')
    .val( function() {
        if ( !$.support.placeholder ) {
            return $(this).attr('placeholder');
        }
    })
    .bind({
        focus: function() {
            var $this = $(this);
            $this.removeClass('hint');
            if ( $this.val() === $this.attr('placeholder') ) {
                $this.val('');
            }
        },
        blur: function() {
            var $this = $(this),
                // Trim whitespace if only space characters are entered,
                // which breaks the placeholders.
                val = $.trim( $this.val() ),
                ph = $this.attr('placeholder');
            if ( val === ph || val === '' ) {
                $this.addClass('hint').val('');
                if ( !$.support.placeholder ) {
                    $this.val(ph);
                }
            }
        }
    });
Add a new validation rule
添加新的验证规则
$.validator.addMethod('notPlaceholder', function(val, el) {
    return this.optional(el) || ( val !== $(el).attr('placeholder') );
}, $.validator.messages.required);
Include the new method in the validate rules object
在验证规则对象中包含新方法
$('form').validate({
    rules: {
        name: {
            required: true,
            notPlaceholder: true
        },
        email: {
            required: true,
            notPlaceholder: true,
            email: true
        }
    }
});
回答by ripper234
I think adding this to jquery.validate.js, to the requiredfunction (line 900), is best:
我认为将此添加到 jquery.validate.js 到required函数(第 900 行)中是最好的:
required: function(value, element, param) {
        // Our change
        if (element.value == element.defaultValue) {
            return false;
        }
        // End our change
回答by Tomasz Maj
Placeholderplugin update solved my issue :)
占位符插件更新解决了我的问题:)
回答by Sara Chipps
you can solve this by binding this to the submit function (either through jQuery validate or manually)
您可以通过将其绑定到提交函数来解决此问题(通过 jQuery 验证或手动)
 if(element.val() == text){
      element.val('');
 }

