0

I am trying to validate text as valid date, but i am getting wrong answers

I tried libraries like moments and date-fns , the text is free so it can be for example : 'eer 05/03/2345', for this text js Date object creates a valid date .

code examples :

var t=moment('43/05/2020','dd/MM/yyyy'); console.log(t.isValid()) //returns true should be false

var t=moment('03/05/2020','dd/MM/yyyy',true); console.log(t.isValid()) //returns false should be true

//using date-fns

console.log(format(new Date('ssds 3/3/2020'), 'dd/MM/yyyy')); //returns true should be false

Omer David
  • 31
  • 1
  • 3

2 Answers2

1

You are using the wrong format. The format tokens are case sensitive.

let t = moment('43/05/2020','DD/MM/YYYY'); 
console.log(t.isValid());

t = moment('03/05/2020','DD/MM/YYYY',true); 
console.log(t.isValid());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

You can get more details over here: docs

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
  • 1
    Your answer is correct but leaving in the comments makes it confusing as they are incorrect. – Jim Oct 23 '19 at 16:06
  • The correct format solved the problem for illegal dates like : moment('43/05/2020','DD/MM/YYYY'); but for this case date is valid moment('hghg 3/05/2020','DD/MM/YYYY'); – Omer David Oct 24 '19 at 17:45
0

There are some post validating dates, if you are using moment take a look at this.

var dateEntered = $('#txtEnteredDate').val();

if (!moment(dateEntered,'MM-DD-YYYY').isValid()) {
  console.log('Invalid Date');
} else {
  console.log('Valid Date');
}

the code above was taken from this url: Managing Dates and Times Using Moment.js

you can also take a look to this url: Javascript - Regex to validate date format