Multiple regex expressions to check mobile number in javascript

24 Views Asked by At

Hi all i have a condition to test international phone number patterns that is(###) ###-####,Currently i have written code for this patter,which is working fine,But i want to allow a pattern also (###)###-#### and it should not accept letters but currently it is accepting,Can somebody please helpme how to achieve this

const phoneNumber = document.getElementById('phone_number').value.trim();

    // Regex pattern for USA phone number
    const pattern = /^\(\d{3}\) \d{3}-\d{4}$/;

    // Validate phone number and update message
    const isValid = pattern.test(phoneNumber);
    document.getElementById('phoneValidationMsg').textContent = isValid ? '' : 'Please enter a valid phone number.';
    return isValid;
1

There are 1 best solutions below

2
Anthony N On

Try the below regular expression:

^\(\d{3}\)\s?\d{3}-\d{4}

I added the "\s?" to the regular expression. It checks for an optional space.