Sunday, March 27, 2022

Validate dd/mm/yyyy on input keyup jQuery

 Format: dd/mm/yyyy

$(document).on("keyup", ".input-date-only", function () {  
   var inputVal = $(this).val();  
   let valid = /^0?$|^(?:0?[1-9]|[12]\d|3[01])(?:\/(?:(?:0$|0?[1-9]|1[012]?)(?:\/\d{0,4})?)?)?$/.test(inputVal), input = inputVal;  
   if (!valid) {  
     alert("Please enter a valid date!");  
     $(this).val(input.substring(0, input.length - 1));  
   }  
 });  

Use the below regex for checking the other formats

 Format: dd-mm-yyyy

^0?$|^(?:0?[1-9]|[12]\d|3[01])(?:-(?:(?:0$|0?[1-9]|1[012]?)(?:-\d{0,4})?)?)?$ 

 Format: mm-dd-yyyy

^0?$|^(?:0?[1-9]|1[012]?)(?:-(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:-\d{0,4})?)?)?$  

 Format: yyyy-mm-dd

^\d{0,4}$|^\d{4}-0?$|^\d{4}-(?:0?[1-9]|1[012])(?:-(?:0?[1-9]?|[12]\d|3[01])?)?$ 

No comments:

Post a Comment