Basically I have an HTML textbox and the user enters digits. What I want is to automatically put a - after the 7th digit Basically have this pattern:
0000000-0000
<input type="text" class="form-control width-160" name="value" required maxlength="10"/>
I'm pretty sure I need to use a regex for this, but can I use it directly in HTML or do I need some jQuery ?
Basically I have an HTML textbox and the user enters digits. What I want is to automatically put a - after the 7th digit Basically have this pattern:
0000000-0000
<input type="text" class="form-control width-160" name="value" required maxlength="10"/>
I'm pretty sure I need to use a regex for this, but can I use it directly in HTML or do I need some jQuery ?
Share Improve this question edited Dec 9, 2020 at 5:55 Ambrish Pathak 3,9682 gold badges17 silver badges30 bronze badges asked May 15, 2017 at 8:22 crystyxncrystyxn 1,6037 gold badges36 silver badges74 bronze badges 4- You know you need regex, but what have you tried so far? – evolutionxbox Commented May 15, 2017 at 8:24
- check this https://github./RobinHerbots/Inputmask – aseferov Commented May 15, 2017 at 8:26
- hey why you down vote my answer it works fine – user8003769 Commented May 15, 2017 at 8:45
- You don't need to use jQuery. – cнŝdk Commented May 15, 2017 at 9:02
4 Answers
Reset to default 7You can use jquery.mask
for this
More info Here
Usage:
<input type="text" class="phone" name="value"/>
$(document).ready(function(){
$('.phone').mask('0000000-0000');
});
See it here live https://jsfiddle/n0oeu3p2/
Try with slice()
and change the input length
is 11
$('input').on('input',function(){
var str = $(this).val().replace('-','');
if(str.length > 7)
$(this).val(str.slice(0,7)+'-'+str.slice(7,str.length))
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control width-160" name="value" required maxlength="11" />
<form action="javascript:alert('Corect!');">
<input type="text" pattern="\d{7}-\d{4}" title="Should be of the format 0000000-0000"/>
</form>
Done! Only with html and regexp
Without the need to use any external library, you can use onkeyup
event and just test if we type the 7th character append -
to the value.
Here's what you will need:
var changeIt = function changeIt(input) {
if (input.value.length === 7) {
input.value = input.value + "-";
}
}
Demo:
Here's a working Snippet:
var changeIt = function changeIt(input) {
if (input.value.length === 7) {
input.value = input.value + "-";
}
}
<input type="text" class="form-control width-160" name="value" required maxlength="12" onkeyup="changeIt(this)" pattern="[0-9]{7}-[0-9]{4}" />
And use [0-9]{7}-[0-9]{4}
too as a regex in the pattern
HTML attribute to make sure your input value matches the Regex 0000000-0000
.