最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Searching validityState for values - Stack Overflow

programmeradmin4浏览0评论

I may be approaching this the wrong way, but I'm confused how to extract information from an input's validityState object.

var input = document.querySelector('#myinput');
var validity = input.validity;
var keys = Object.keys(validity);

console.log( validity );          // [ object validityState ]
console.log( validity.valid );    // false (this is expected)

console.log( keys )               // empty array
console.log( keys.length )        // 0
<input type="text" id="myinput" required>

I may be approaching this the wrong way, but I'm confused how to extract information from an input's validityState object.

var input = document.querySelector('#myinput');
var validity = input.validity;
var keys = Object.keys(validity);

console.log( validity );          // [ object validityState ]
console.log( validity.valid );    // false (this is expected)

console.log( keys )               // empty array
console.log( keys.length )        // 0
<input type="text" id="myinput" required>

My main question is, how do I find out which property is "failing" if I can't iterate over the validityState object?

Am I missing something?

Share Improve this question asked Oct 25, 2016 at 11:17 evolutionxboxevolutionxbox 4,1326 gold badges38 silver badges57 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

Do not use Object.keys(). You can simply iterate on your validity state like this:

var input = document.querySelector('#myinput');
var validity = input.validity;
for(var key in validity){
     console.log(key + ": " + validity[key]);
}
<input type="text" id="myinput" required>

Edit:

  • Object.keys() only referring to keys that are in the current Object and does not look in the prototype of this Object. Note that object.hasOwnProperty() does the same test

  • in return true if the property is present in the current Object OR if the property is present in the prototype

发布评论

评论列表(0)

  1. 暂无评论