WNR*_*erg 6 html javascript validation jquery placeholder
我正在使用jQuery Validation插件来验证我网站上的表单.
http://docs.jquery.com/Plugins/Validation
我还使用以下代码为不支持HTML5 placeholder=""
属性的浏览器提供Placeholder支持.
// 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('');
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
当我提交表单时,会发生以下情况:
在支持该placeholder
属性的浏览器中,该validate()
函数会触发,并且一切都按预期运行.
在不支持该placeholder
属性的浏览器中,第20-25行清除所有"占位符",然后validate()
触发该函数.如果没有错误,页面提交并且一切都按预期工作.
在不受支持的浏览器中,如果存在错误,则会class="error"
像往常一样应用相应的字段- 但是在blur()
特定字段上发生事件之前,占位符文本不会返回.这placeholder
会将这些字段留空 - 因为没有标签(只是属性),所以用户可以猜测每个空字段应包含的内容,直到blur()
事件发生.
不支持的浏览器的另一个问题是,由于占位符修复修改了value
属性以显示占位符,因此标记为必需的字段在失败时会通过验证.
似乎没有简单的方法将Validation插件与占位符支持代码一起使用.
我正在寻找修改占位符支持代码或添加submitHandler: {}
函数作为函数的参数,以validate()
使其在不受支持的浏览器中工作.
小智 7
我遇到了类似的问题.你有没有上班的?我很想比较笔记.
FWIW,这就是我的所作所为:
将输入占位符添加到jQuery支持对象:
$.support.placeholder = (function() {
var i = document.createElement( 'input' );
return 'placeholder' in i;
})();
Run Code Online (Sandbox Code Playgroud)
占位链:
$('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);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
添加新的验证规则
$.validator.addMethod('notPlaceholder', function(val, el) {
return this.optional(el) || ( val !== $(el).attr('placeholder') );
}, $.validator.messages.required);
Run Code Online (Sandbox Code Playgroud)
在验证规则对象中包含新方法
$('form').validate({
rules: {
name: {
required: true,
notPlaceholder: true
},
email: {
required: true,
notPlaceholder: true,
email: true
}
}
});
Run Code Online (Sandbox Code Playgroud)
您可以通过将其绑定到提交函数来解决此问题(通过 jQuery 验证或手动)
if(element.val() == text){
element.val('');
}
Run Code Online (Sandbox Code Playgroud)