To validate a phone number in JavaScript, you can use regular expressions (regex). Here's an example function that checks whether a phone number has 10 digits:
index.tsx258 chars9 lines
This function uses the test()
method of the regex object to check if the input string matches the pattern defined by the regular expression. The ^\d{10}$
pattern specifies that the input string should start (^
) and end ($
) with exactly 10 digits (\d
). You can adjust the regular expression pattern to match your specific validation requirements.
To use this function in your web application, you can call it when the user submits a form or enters text in an input field, like this:
index.tsx399 chars13 lines
Note that this example only checks whether the phone number has 10 digits, but it doesn't validate other aspects of a phone number such as country code or area code. Depending on your requirements, you may need to use a more complex regular expression or a library for phone number validation.
gistlibby LogSnag