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 with7
,8
or9
, and then contains any 8 digits. It checks the final format, thepattern
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 wantpattern
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
1 Answer
Reset to default 1Pattern 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;
});
})();