in a django template with the html pattern tag and boostrap for form validation
with this regex it validates a sequence of numbers that can be separated by a dash
"^[ -]?\d(?:-?\d) $"
example:
12-65-25-75-84 or 12-255-0214
the javascript :
(() => {
'use strict'
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
and the html
<input type="text" id="exampleFormControlInput1" name="tel" id="tel" placeholder="Tel" pattern="^[ -]?\d(?:-?\d) $" required>
</div>
I would like to know how to modify it to have the possibility of putting spaces between the numbers (in addition to the dashes)
example:
12 57 125-98-457
and limit the total number of digits to 15 (excluding spaces and dashes)
for example a string like this:
12-28-35-74-12
or
12 28 35 74 12
or 123-478 25 12 124-15
thank you
CodePudding user response:
I would use:
^[0-9](?:[ -]?[0-9]){0,14}$
^
- Matches the start of the string.[0-9]
- Matches a single digit (0, 1, ... 9).(?:
- Start of a non-capturing group.[ -]?
- Optionally matches either a space or '-'.[0-9]
- Matches a single digit (0, 1, ... 9).)
- End of the non-capturing group.{0,14}
- Maches the previous token, i.e. the previous non-capturing group, from 0 to 14 times.$
- Matches the end of the string.