skip to Main Content

Screenshot
How to validate dd-mm-yyyy with regex, currently I have got yyyy-mm-dd but not able to find for dd-mm-yyyy. Please help as I need on validate on every keyup

jsFiddle

$("#date").on("keyup", function()
{
    let valid = /^d{0,4}$|^d{4}-0?$|^d{4}-(?:0?[1-9]|1[012])(?:-(?:0?[1-9]?|[12]d|3[01])?)?$/.test(this.value), input = this.value;
    
    if(!valid) {
        this.value = input.substring(0, input.length - 1);
        this.style.backgroundColor = '#EEA39C';
    }
    setTimeout(() => { this.style.backgroundColor = '#88DD85'; }, 700);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="date" style="font-size: 20px" maxlength="10" type="text" />

2

Answers


  1. You should not use Regex to validate if date is actually valid. Use JS logic for that, e.g. momentJs library

    function validateDate(el) {
      let date = $('#date').val();
      let format = $('#format').val();
      let isValid = moment(date, format).isValid();
    
      alert('Date ' + date + ' is ' + (isValid ? 'valid' : 'invalid') + ' for format ' + format);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
    
    <select id="format" onChange="validateDate()">
      <option value="YYYY-MM-DD">yyyy-mm-dd</option>
      <option value="DD/MM/YYYY">dd/mm/yyyy</option>
      <option value="MM/DD/YYYY">mm/dd/yyyy</option>
    </select>
    
    <input id="date" type="text" onChange="validateDate()"/>
    Login or Signup to reply.
  2. This regex check the whole Gregorian rule. you can try this.

     regExp = "(((d{2}(([13579][26])|([2468][480])|(0[48])))|(([13579][26])|([02468][480]))00)-02-29)|(d{4}-((?:(0[13578]|1[02])-([0-2]d|3[0-1]))|(?:(0[469]|11)-([0-2]d|30))|(?:02-([0-1]d|2[0-8]))))"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search