'How to validate date as characters are entered in js
There is an input where the user must enter a date in the format dd.mm.yyyy., And I need to check that he does not write letters and other unnecessary characters. The Internet is full of examples for a ready-made date, in my case it is necessary to check as you enter. For example, the user pressed the key 2 - it appeared in the input, pressed z - nothing changed in the input. Pressed 3 - ok, pressed / - nothing has changed. I tried to write a regular expression,
((0[1-9]{0,1})|([1-2][0-9]{0,1})|(3[0-1]{0,1}))\.{ 0.1}
but I can't figure out how to check the data after the dot. Need your advice.
Here is a small example
Solution 1:[1]
Just updated you tags on question, as your linked example was using React, and how you do this in plain JS would be slightly different.
Rather than regEx, a slightly easier option might be to use lookups, you could then check what valid chars are available at each char position.
Below is an example.
ps. It won't catch everything, eg. 31 days in Feb, & 29/28 for leap years etc. So ideally you should check again after date fully entered.
const {useState} = React;
const anynum = '01234567890';
const num01 = '01';
const num31 = '0123';
const dot = '.';
const posValid = [
num31, //3
anynum, //1
dot, //.
num01, //1
anynum, //2
dot, //.
anynum, //2
anynum, //0
anynum, //2
anynum //2
]
function partsValid(s) {
if (s.length > posValid.length) return false;
//simple num check at pos
for (let l = 0; l < s.length; l += 1) {
const c = s[l];
if (!posValid[l].includes(c)) return false;
}
//check day
if (s.length > 1) {
const day = parseInt(s.slice(0, 2), 10);
if (!(day >= 1 && day <= 31)) return false;
}
//check month
if (s.length > 4) {
const month = parseInt(s.slice(3, 5), 10);
if (!(month >= 1 && month <= 12)) return false;
}
return true;
}
function App() {
const [value, setValue] = useState("");
const onchange = (e) => {
const nv = e.target.value;
if (partsValid(nv)) setValue(nv);
};
return (
<div>
<input onChange={onchange} value={value} placeholder="dd.mm.yyyy" />
</div>
);
}
ReactDOM.render(<App/>, document.querySelector('#mount'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="mount"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
