I want to make sure that the credit card expiration date entered by the user should be in format MM/YYYY and the range of MM is between 01 and 12, and YYYY is between 2016 and 2031 (inclusively).
How do I do that using pattern matching in HTML 5?
I tried the following but didnt work:
<input type="text" pattern="\d{1,2}/\d{4}" name="date" value="" />
CodePudding user response:
Your pattern is slightly incorrect.
You need to place the input inside form and you can't submit the form.
Remove the 1, in month regex because you only want to accept 2 digit of number.
If you want number range I think it's better to use javascript
To set validation error in input you can use setCustomValidity
const datePickers = document.querySelectorAll('.datepicker')
datePickers.forEach(picker => {
picker.addEventListener('input', (event) => {
const value = event.target.value
if (!/\d{2}\/\d{4}/g.test(value))
return event.target.setCustomValidity('Invalid Date')
if (!value.includes('/'))
return event.target.setCustomValidity('Invalid Date')
const [month, year] = value.split('/')
const monthInt = parseInt(month, 10)
const yearInt = parseInt(year, 10)
if (monthInt < 0 || monthInt > 12)
return event.target.setCustomValidity('Invalid Month')
if (yearInt < 2016 || yearInt > 2031)
return event.target.setCustomValidity('Invalid Year')
event.target.setCustomValidity('')
})
})
<form>
<input type="text" name="date" value="" />
<button type="submit">submit</button>
</form>