-4

I am working on an HTML website and I am a little stuck in one situation.

The client wants to add phone numerical numbers only, without alphabetic characters with the condition that the phone number field should be accepted and submit phone number if someone enters +91 in front of 10 digit phone number (i.e +917894561236) and if he didn't add +91 the field should also accept 10 digit phone number but not less than 10 numbers.

Here is my html:

<div class="form-group">
  <label for="">Phone number *</label>
  <input type="text" class="form-control" minlength=10 required name="phone_m" id="phoned"
         placeholder="Enter Your Phone Number" pattern="^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$"
         oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}" / >
</div>

The below jQuery script is used to remove alphabets from phone field, however adding type="tel" in input field dosn't stop users to type alphabets

<script>
//to get only numeric values in phone number field
jQuery('#phoned').keyup(function () { 
    this.value = this.value.replace(/[^0-9+\.-]/g, '');
});
</script>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • 1
    your input should be `type='tel'` and you can add a `pattern` attribute which takes a Regex to meet your requirements. If you do this, you can remove `maxlength` and your placeholder should match your expected pattern to not confuse users. – lbragile Nov 11 '20 at 06:28
  • 3
    Use **Regular Expressions** for your desired result. Remove ``maxlength`` as then you cannot accept ``+91`` or use ``manlength`` as 13( 10 digits for mobile number and 3 digits/char for +91 ). You can use ``minlength`` as 10 as alteast you need 10 digit mobile number. For matching mobile number you can use ``[6-9]{1}[0-9]{9}`` where number start from 6 or 7 or 8 or 9 and rest other 9 digits can be any. For matching **+91** you can do similar thing – Not A Bot Nov 11 '20 at 06:32
  • @Cre you must not sprinkle code requirements all over the page. Your question would be more clear if you offered a few sample strings that should and should not be allowed. You are receiving diwnvotes because there is no evidence that you have researched and tried to self-solve. We are not meant to "do your work for you", we are here to help you fix your failed attempts. "Help Vampirism" is bad. – mickmackusa Nov 11 '20 at 08:22
  • 1
    @Don please avoid editing closed questions unless the edit makes the question a good candidate for reopening. The reason that I say this is because your edit has placed this question in the Reopen Queue, but the OP needs to offer some more clarity/details. – mickmackusa Nov 11 '20 at 08:34
  • I see, sorry about that. It came up in the suggested edits review queue. I approved the edit, but improved it myself. Will take note to avoid editing closed questions, thanks for pointing that out. – Don't Panic Nov 11 '20 at 10:22
  • Please read [ask]. You may also want to include a description of the problems with the code you've supplied. – Mick Nov 13 '20 at 06:44
  • Does this answer your question? [Validate phone number with JavaScript](https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript) – Dharman Nov 14 '20 at 19:34

3 Answers3

3

Try this one this will work, same i used for my client

<div class="form-group">
  <label for="phone">Enter your phone number:</label>
    <input type="text" class="form-control" title="please enter a valid phone number" pattern="^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$" oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}" />
</div>
Merin Ovelil
  • 367
  • 2
  • 9
1

As per my comment above, try this:

<div class="form-group">
  <label for="phone">Enter your phone number:</label>
  <input type="tel" id="phone" name="phone" placeholder="+910123456789 or 0123456789" pattern="[+0-9]{10,13}">
</div>

You can test Regex here: https://regex101.com/

function displayInputValue() {
  console.log(document.querySelector("input[type='tel']").value)
}
<div class="form-group">
  <label for="phone">Enter your phone number:</label>
  <input type="tel" id="phone" name="phone" placeholder="+910123456789 or 0123456789" pattern="[+0-9]{10,13}">
  <button type="button" onClick="displayInputValue()">Show Value</button>
</div>
lbragile
  • 7,549
  • 3
  • 27
  • 64
0

I wrote and used this function for my client, it formats while they type it, and actually check if the char entered is numerical, trims the lenght as well. Well the format they wanted is "XXX-XXX-XXXX" but I am sure you can mod my code to suite your needs. The regex is not perfect but if they copy and past s*** it will stop them from submitting.

document.getElementById("phone").onkeyup = function()
{
    const CHAR_AMOUNT = this.value.length;
    // Check each character as the user types it, do not exceed the format we want of "XXX-XXX-XXXX".
    if (CHAR_AMOUNT < 13)
    {
        // Get the position of the last char, and check if the string has at least 1 char.
        // THAN get the last character typed by the user and check if it is a valid numerical type, if not, get rid of it.
        const LAST_CHAR_POS = CHAR_AMOUNT - 1;
        if (LAST_CHAR_POS >= 0)
        {
            const LAST_CHAR = this.value.charAt(LAST_CHAR_POS);
            if (isNaN(LAST_CHAR))
            {
                this.value = this.value.slice(0, -1);
                return;
            }
        }
        // Here we auto fill the '-' char after the 3rd and 7th digit of the phone number.
        if ((CHAR_AMOUNT === 3) || (CHAR_AMOUNT === 7))
        {
            this.value += "-";
        }
    }
    else // Trim any excess characters on the phone number. including if someone is copy and poaste a long string.
    {
        this.value = this.value.slice(0, (12 - CHAR_AMOUNT));
        // Ho well, if they copy past garbadge, let the HTML pattern stop them from submitting (-_-).
    }
    return;
};
<input type="tel" id="phone" pattern="\d{3}-\d{3}-\d{4}" placeholder="123-456-7890" title="Must be XXX-XXX-XXXX" required />
Dominick
  • 31
  • 7