2017-08-06 90 views
1

你好每一個身體我需要時刻JS幫我叫開始輸入場和另一個叫停止之間的差異用2 JS時刻

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例如:當我刪除輸入的值如下圖所示爲6:39 PM,輸入例如6:02:00 PM or 1:00 PM or添加一個字符串5:dfds2 PM i想要控制檯記錄任何錯誤消息and return the previous value to the input again也當我刪除當前值並添加一個數字,如'1例如'withou牛逼am or pm所以它決定如果數字是之前或之後比停止輸入值和類型在這樣1:00 AM or 1:00PM我用這個功能來驗證開始輸入字段輸入字段,但它給了我錯誤的答案

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我的想法是從那裏取得的 任何幫助?! thanx提前

+0

您的支票,如果'val'是有效的在這一行上:'moment(val,「hh:mm」)。isValid()'。你的意思是檢查你的'inputVal'? – enjoylife

+0

@enjoylife當然這裏'val == inputVal'我更新了我的問題thx。 –

回答

1

我繼續清理你的函數一點,減少了邏輯,現在你應該只需確保時刻格式是你想找的

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

thx,但是當我輸入像這樣完全'5:bgb2'輸入是'05:02 AM'這是不正確的,因爲有'bgb'這使輸入無效,甚至當我輸入'5:10:'it也用這個值替換輸入字段,這是不正確的任何想法在第二個條件'else'我想採取的開始價值是前例如'1:25 Am',如果我在輸入字段中寫任何它返回無效值'1:25 Am'再次回到輸入而不是t'temp'的值。 –

+0

thanx,但你可以閱讀以上評論 –