Other way to validate a input with html5 regex, with javascript
Other way to validate a input with html5 regex, with javascript
i need to check a html input with a regex pattern with vanilla javaScript, but it's a little bit tricky, i go back to the parent to validate the input, it works but it's not beautiful as expected.
Js:
input.parentNode.querySelector(':valid')
Html:
<input type="tel" id="fos_user_registration_form_mobileNumber" name="fos_user_registration_form[mobileNumber]" required="required" pattern="^0[0|1|2|3|4|5|6|7|9]d8$" maxlength="10">
Is it possible to do otherwise ?
input
1 Answer
1
I think you're looking for the validity
property:
validity
The validity attribute's getter must return a ValidityState
object that represents the validity states of this element. This object is live.
ValidityState
...where one of the states is a boolean valid
flag:
valid
if (input.validity.valid)
// yes
else
// no
Or matches
:
matches
if (input.matches(":valid"))
// yes
else
// no
Thanks a lot! it's very usefull
– Mathieu Maniga
Aug 30 at 15:09
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Are you sure you need to go back to the parent? The
input
cannot have any children, thus hopping to the parent from the input seems wrong if you need validity of the input.– Lazar Ljubenović
Aug 30 at 14:19