skip to Main Content

When inputing string with number the new Date() is missbehaving, is there another way how to achieve this without regex?

let string = 'some string 1';
let invalid = new Date(string);

it is still parsing as a Date value

Mon Jan 01 2001 00:00:00 GMT+0000 (Greenwich Mean Time)

I’m expecting it as an invalid date

2

Answers


  1. Chosen as BEST ANSWER

    Update

    let string = 'some string 1';
    let invalid = new Date(string.replace(/s/g, ''));
    

    Seem to resolve to Invalid Date as i want to and it seem to proper validate all dates also human readable dates like Sun, 1 Dec 2024


  2.     function validateDate(dateString) {
      // Attempt to parse the date string
      const timestamp = Date.parse(dateString);
      
      // Check if the parsed timestamp is NaN (invalid date)
      if (isNaN(timestamp)) {
        return 'Invalid string';
      }
      
      // Convert the timestamp back to a date string
      const date = new Date(timestamp);
      const dateISO = date.toISOString().slice(0, 10); // Extract the YYYY-MM-DD part
      const timeISO = date.toISOString(); // Full ISO format
      
      // Compare the original string with the formatted date strings
      if (dateString === dateISO || dateString === timeISO) {
        return 'Valid date';
      }
      
      return 'Invalid string';
    }
    
    let string = 'some string 1';
    let invalid = validateDate(string);
    

    Now the function will return the date is valid or not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search