I need to validade date yyyy-mm-dd on user keyup.
I'm currently at validating yyyy-mm with this Regex
^\d{0,4}$|^\d{4}[-]$|^\d{4}[-](0?[0-9]|1[012])$
But I need validade others part of date. Can anyone help me?
I need to validade date yyyy-mm-dd on user keyup.
I'm currently at validating yyyy-mm with this Regex
^\d{0,4}$|^\d{4}[-]$|^\d{4}[-](0?[0-9]|1[012])$
But I need validade others part of date. Can anyone help me?
Explanation: Vague checking input while typing if it matches the desired format yyyy-mm-dd
.
Modified your current regex a bit and added the dd
part so it becomes
^\d{0,4}$|^\d{4}-0?$|^\d{4}-(?:0?[1-9]|1[012])(?:-(?:0?[1-9]?|[12]\d|3[01])?)?$
(?:
opens a non capture group for alternation0?[1-9]?
optional 1-9 with preceding 0 or zero[12]\d
days 10-293[01]
days 30 and 31For dd-mm-yyyy
try this variant:
^0?$|^(?:0?[1-9]|[12]\d|3[01])(?:-(?:(?:0$|0?[1-9]|1[012]?)(?:-\d{0,4})?)?)?$
Or for mm-dd-yyyy
that one:
^0?$|^(?:0?[1-9]|1[012]?)(?:-(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:-\d{0,4})?)?)?$
This does not actually validate a date (leap years/28-31 days). Just loose checks input while typing, you can probably make it shorter. As follows an example with the yyyy-mm-dd
pattern.
$("#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/3.3.1/jquery.min.js"></script>
<input id="date" style="font-size: 20px" maxlength="10" type="text" />
To validate the full date when typed/submitted see this answer of @PhiLho and rearrange it to the desired format, e.g. for yyyy-mm-dd
function isValidDate(date)
{
var matches = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(date);
if (matches == null) return false;
var y = matches[1];
var m = matches[2] - 1;
var d = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
<input type="text" id="date" style="font-size: 17px" value="2016-03-16">
<button onclick="alert(
isValidDate(getElementById('date').value)
);" style="font-size: 17px">check date</button>
This regex is a bit complex, but check the whole Gregorian rule.
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]))))"
var regExp = /^(\d{4})-(\d{2})-(\d{2})$/
regExp.test(value);