验证空日期输入?

我只是想在插入对象之前检查 atext和input 是否不为空。date如果它们都是空的,我希望它们不要添加到其中。然而,我所做的任何尝试,它们仍然被添加到没有任何价值的对象中。


for(let i = 0; i < otherDeps.length; i++) {

      let obj;

      if(otherDeps[i].name && otherDeps[i].dob != "") { //Here

        obj = {

          name: otherDeps[i].value,

          dob: otherDepsAge[i].value

        };

      }

      otherDepsArray.push(obj);

    }

我已经尝试过了if(!otherDeps[i].date),ìf(otherDeps[i]name != '' && otherDeps[i].date != '0000-00-00')


有人知道解决这个问题的正确方法吗?


婷婷同学_
浏览 103回答 2
2回答

忽然笑

您需要检查以下两个条件来检查日期是否无效或不正确:theDate.valueisNaN(new Date(theDate).getTime())从这个角度来看,我们可以做这样的事情:function checkDate() {&nbsp; var theDate = document.getElementById("date").value;&nbsp; if (theDate.trim() === "" || isNaN(new Date(theDate).getTime())) {&nbsp; &nbsp; console.log("Invalid Date!");&nbsp; } else {&nbsp; &nbsp; console.log("Valid Date!");&nbsp; }}<input type="date" id="date" /><button onclick="checkDate()">Check Date</button>在for循环中,将日期值包含在checkDate()上面的条件内。这应该有效。

慕运维8079593

如果要检查输入的日期是否无效或为空,可以使用 HTMLInputElement 的validity.badInput 属性:submit = () => {&nbsp; &nbsp; const date = document.getElementById('my-date');&nbsp; &nbsp; if (date.value === '') {&nbsp; &nbsp; &nbsp; if (date.validity.badInput) {&nbsp; &nbsp; &nbsp; &nbsp; console.log('Invalid');&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; console.log('Blank');&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; console.log(date.value);&nbsp; &nbsp; }&nbsp; }<input type="date" id="my-date" /><button onClick="submit()">Submit</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript