rango rango - 4 months ago 26
Javascript Question

date validation pseudocode to javascript

I am having trouble converting this pseudocode statement to javascript i am new to javascript and i am confused on labling the string and i want to make sure i am on the right track

// 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


this is my javascript translation

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;

Answer

Here is your function:

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(parseFloat(mm) != parseFloat(mm) ||
     parseFloat(dd) != parseFloat(dd) ||
     parseFloat(yyyy) != parseFloat(yyyy)){
    return false;
  } 
  if(parseFloat(mm) < 1 || parseFloat(mm) > 12 || parseFloat(dd) < 1 || parseFloat(dd) > 31){
    return false;
  }
  return true;
};

console.log(isValidDateFormat("foobarbaz"));
console.log(isValidDateFormat("09-21-1989"));
console.log(isValidDateFormat("88/88/8888"));
console.log(isValidDateFormat("04/12/1967"));