2016-07-30 98 views
1

我有麻烦这个伪言转换为JavaScript我是新来的JavaScript和我感到困惑的labling串,我想确保我在正确的轨道日期验证伪代码的JavaScript

// Date validation function 
Function Boolean isValidDateFormat(String str) 
// Declare variables 
Declare String mm, dd, yyyy // month, day, year 
Declare Boolean result = True // valid date format 
// Check that length of string is 10 
If length(str) != 10 Then 
result = False 
End If 
// Check that third and sixth characters are slashes 
If substring(str,2,1) != "/" Or 
substring(str,5,1) != "/" Then 
result = False 
End If 
// Separate string into parts 
// Check that all entries are numeric 
mm = substring(str,0,2) // month 
dd = substring(str,3,2) // day 
yyyy = substring(str,6,4) // year 
If Not isNumeric(mm) Or Not isNumeric(dd) 
Or Not isNumeric(yyyy) Then 
result = False 
End If 
// Check that month is between 1 and 12 
// and day is between 1 and 31 
If (mm < 1 Or mm > 12) Or (dd < 1 Or dd > 31) Then 
result = False 
End If 
Return result 
End Function  

上这是我的JavaScript翻译

function isValidDateFormat(String str){  
    return false;  
if (str.length <10) 
    return false; 
dd= substr[0];    
    mm= substr[3];  
    yyyy= substr[6]; 
if substr [2]!= "/"; 
    substr [5]!= "/"; 
return false; 

if (mm < 1 || mm > 12) 
    return false; 
else if (dd < 1 || dd> 31) 
    return false; 
+2

有几个问题,包括语法,而是着眼于这一个第一:该函数什么都不做,因为它做的第一件事是“返回false”。 –

+0

'String str'无效JavaScript。它应该是'str'。 – Xufox

+0

你有很多非常基本的错误,我建议你先阅读JavaScript。你也应该注意到这是一个非常简单的验证器;例如,它将在二月三十一日通过有效。 – Shaggy

回答

1

这里是你的函数:

function isValidDateFormat(str){ 
 
    var mm, dd, yyyy; 
 
    if(str.length != 10){ 
 
    return false; 
 
    } 
 
    if(str.charAt(2) != "/" || str.charAt(5) != "/"){ 
 
    return false; 
 
    } 
 
    mm = str.substring(0,2); 
 
    dd = str.substring(3,5); 
 
    yyyy = str.substring(6,10); 
 
    if(parseInt(mm) != parseInt(mm) || 
 
    parseInt(dd) != parseInt(dd) || 
 
    parseInt(yyyy) != parseInt(yyyy) || 
 
    parseFloat(yyyy) % 1 != 0){ 
 
    return false; 
 
    } 
 
    if(parseInt(mm) < 1 || 
 
    parseInt(mm) > 12 || 
 
    parseInt(dd) < 1 || 
 
    parseInt(dd) > 31){ 
 
    return false; 
 
    } 
 
    return true; 
 
}; 
 

 
console.log("is foobarbaz valid? " + isValidDateFormat("foobarbaz")); 
 
console.log("is 09-21-1989 valid? " + isValidDateFormat("09-21-1989")); 
 
console.log("is 88/88/8888 valid? " + isValidDateFormat("88/88/8888")); 
 
console.log("is 09/21/19.9 valid? " + isValidDateFormat("09/21/19.9")); 
 
console.log("is 04/12/1967 valid? " + isValidDateFormat("04/12/1967"));

有不同的方法来检查,如果一个字符串包含一个数字,在这里我使用a != a赶上NaN的。

注意:这将返回true,与原来的伪代码:

console.log(isValidDateFormat("09/21/19.9")); 

所以,你必须更改代码,以检查是否字符串包含只有数字(因为,毕竟,19.9是一个号码...)。要做到这一点的方法之一是检查剩余:

parseFloat(yyyy) % 1 != 0