使用时刻js

时间:2017-08-06 00:48:15

标签: javascript momentjs

大家好我需要帮助的时刻js我有一个名为Start的输入字段和另一个名为stop的输入字段

start = moment().format('LT'); // works when i click on the play button
stop  = moment().format('LT'); // works when i focus on the counter input beside the play button --> for test

我想手动更改开始输入字段,所以我想要一个验证函数,它接受输入值并检查输入是否有效在此表单LT上为ex:当我删除值时在图片和类型中输入6:39 PM如下6:02:00 PM or 1:00 PM or添加字符串5:dfds2 PM我想要控制台记录任何错误消息and return the previous value to the input again当我删除当前值时并添加一个类似&#39; 1的数字&#39; 1没有am or pm所以它确定数字是否在停止输入值之前或之后,并在输入字段中键入,如1:00 AM or 1:00PM我使用此函数来验证开始输入字段,但它给出了错误答案< / p>

function validate(inputVal) {
  let temp =this.startTime;
  let x = temp;
  if(moment(inputVal, "hh:mm").isValid()) {
    x= moment(inputVal, "HH:mm").format('hh:mm A');
    console.log("inputVal is: " + inputVal + " and x is: " + x);
    this.startTime = x
  } else {
    this.startTime = "temp";
    console.log("no");
  }
}  

这是照片 enter image description here 欲了解更多信息,你可以访问toggl website我的想法是从那里获取的 任何帮助?!提前谢谢

1 个答案:

答案 0 :(得分:1)

我继续清理你的功能,减少了逻辑,现在你应该确保时刻格式是你想要的

function validate(val) {
    let parsedTime = moment(val, "hh:mm");
    if (parsedTime.isValid()) {
        this.startTime =  parsedTime.format('hh:mm A');
    } 
}  
相关问题