0

I have a form in Angular4, with 2 dates: started, finished.

I want to check that the format date is dd/mm/yyyy.

I wrote:

     <input  pattern="((0)*[1-9]|[1-2][0-9]|(3)[0-1])(\/)(((0)*[1-9])|((1)[0-2]))(\/)\d{4}$" [(ngModel)]="filterDateStart" class="form-control" type="date" id="filterDateStart" name="filterDateStart"  clrDate>

    <input   pattern="((0)*[1-9]|[1-2][0-9]|(3)[0-1])(\/)(((0)*[1-9])|((1)[0-2]))(\/)\d{4}$" [(ngModel)]="filterDateEnd" class="form-control" type="date" id="filterDateEnd" name="filterDateEnd"  clrDate>

Then when I write invalid dates , my html doesn't say anything... I can send this form.

enter image description here

Then I need to check these dates.

 1º Date start < date end
 2º Ranges valid -> (30/20/2018) or (32/12/2018)

I see the library moment.js, but my boss says that I don't should be it. thanks, sorry for my english.

Aurelian
  • 15
  • 7
EduBw
  • 866
  • 5
  • 20
  • 40
  • Since you are using angular 4 apparently, i'd rather reccomend using Validators in the form. Use a pattern validator to check for your format, and others for range, etc. https://stackoverflow.com/questions/37859790/validation-pattern-for-date-in-dd-mm-yyyy-format-using-angular2/37860088#37860088 – Agash Thamo. Oct 24 '18 at 10:34

1 Answers1

1

Don't use regexes, rely on the Date API :

const valid = '12/12/2018';
const invalid1 = '12/12';
const invalid2 = '12.12.2018';
const invalid3 = 'foo';

function parseDate(date) {
  try {
    // Make your business logic here. Examples : all must be defined and numbers, and separated with a /
    const [d, m, y] = date.split('/');
    
    if (!d || !m || !y) throw new Error();
    
    if(isNaN(d) || isNaN(m) || isNaN(y)) throw new Error();
    
    return new Date(y, m, d);
  } catch(err) {
    return 'Invalid date';
  }
}

console.log(parseDate(valid));
console.log(parseDate(invalid1));
console.log(parseDate(invalid2));
console.log(parseDate(invalid3));

With that you can create a custom validator, that will be a lot more explicit than using a pattern.

  • new Date(y, m, d) --->>> 30/02/2008, should be error --but not --> Sun Mar 30 2008 00:00:00 GMT+0100 (hora estándar de Europa central) – EduBw Oct 24 '18 at 13:49
  • it's working with my code because I only put two conditions in it. I'm giving a direction to follow, I'm not a code monkey. –  Oct 24 '18 at 14:59
  • https://stackoverflow.com/questions/52970849/i-can-created-date-30-02-yyyy-with-typescript?noredirect=1#comment92850824_52970849. Sorry – EduBw Oct 24 '18 at 15:03