最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Allow typing mobile numbers starting with 7,8 or 9 - Stack Overflow

programmeradmin0浏览0评论

I need the realtime validation to use in the input tag to allow user typing only the number starting with 7,8 or 9. right now I have the following thing which is not working. Only if the user types the digits 7 to 9 as the first digit on the input field then only it should be appearing in the input field.

<input type="tel" label="Mobile Number" pattern="^[7-9][0-9]{8}$" maxLength="10"/>

I need the realtime validation to use in the input tag to allow user typing only the number starting with 7,8 or 9. right now I have the following thing which is not working. Only if the user types the digits 7 to 9 as the first digit on the input field then only it should be appearing in the input field.

<input type="tel" label="Mobile Number" pattern="^[7-9][0-9]{8}$" maxLength="10"/>
Share Improve this question edited Sep 30, 2017 at 11:20 Subhojit asked Sep 29, 2017 at 10:23 SubhojitSubhojit 1,5418 gold badges21 silver badges38 bronze badges 11
  • 2 The ^[7-9][0-9]{8}$ pattern matches a string that starts with 7, 8 or 9, and then contains any 8 digits. It checks the final format, the pattern attribute is not usually used for live input validation. At any rate, you seem to want to use ^[7-9]\d{0,8}$ pattern. – Wiktor Stribiżew Commented Sep 29, 2017 at 10:25
  • it's still allowing to type the number 0-6 as first digit in the input field. – Subhojit Commented Sep 29, 2017 at 10:28
  • Yeah, because you need to use type="text" if you want pattern to work at all. – Wiktor Stribiżew Commented Sep 29, 2017 at 10:29
  • Define "not working". It works fine for me. i.imgur./8i5WAJk.png – Quentin Commented Sep 29, 2017 at 10:30
  • I changed it's type to text from tel and used your given pattern. But it's same as before. not working.. – Subhojit Commented Sep 29, 2017 at 10:31
 |  Show 6 more ments

1 Answer 1

Reset to default 1

Pattern on input is validated only on submit.

If you want to validate on real time, You can achieve it using javascript

(function() {
    var input = document.getElementById('YOUR_INPUT_ID');
    var pattern = /^[7-9][0-9]{0,8}$/;
    var value = input.value;
    !pattern.test(value) && (input.value = value = '');
    input.addEventListener('input', function() {
        var currentValue = this.value;
        if(currentValue && !pattern.test(currentValue)) this.value = value;
        else value = currentValue;
    });
})();
发布评论

评论列表(0)

  1. 暂无评论