javascript – Validate phone and cell number

Question:

I am validating a field that can be a telephone number or cell phone number, but at the moment of placing the value it accepts me from 7 to 9, I want it to be validated only if it has 7 or 9 characters. How can i fix it?

\d{7,9}

Code

$(document).ready(function () {

var telefono = $("#campo_telefono")

var expreg = /\d{7,9}/;

if (expreg.test(telefono))
    alert("El telefono es correcta");
else
    alert("El telefono NO es correcta"); 
});

Answer:

This expression is valid: only digits from 0 to 9 and between braces ({N, M}) range of number of digits; example: 7 to 9 digits.

^[0-9]{7,9}$

If you only need a number of digits; example: only 7 digits.

^[0-9]{7}$

If you need exact number of digits; example: only 7 or 9 digits.

^(\\d{7}|\\d{9})$
Scroll to Top