Reputation: 405
I have an input field which already force a user to enter 8 digits, but i want to force him to enter the digits starts with 2 as give him an alert when enter the first number wrong, if he wrote 2 then let him enter the rest of number. here is my code :
HTML
<input type="number" maxlength="8" class="form-control myInput" name="myInput" id="myInput" placeholder="myInput" pattern="\d{8}" required>
</div>
JQuery
$(".myInput").unbind('keyup change input paste').bind('keyup change input paste',function(e){
var $this = $(this) ,val = $this.val(),valLength = val.length, maxCount = $this.attr('maxlength');
if(valLength>maxCount){
$this.val($this.val().substring(0,maxCount));
}
});
Please help.
Upvotes: 0
Views: 971
Reputation: 407
here is my solution
Jquery
$("#myInput").on('keypress', function(){
var numbers = $(this).val().trim();
if(numbers[1]){
if(numbers[0] != '2' || numbers.length > 8){
$(this).val('');
$('.error').html("Error the input has to start with number 2 and has to be lesser than 8 numbers");
}else{
$('.error').html("Good");
}
}
});
html
<input type="number" maxlength="8" id="myInput" required>
<div class='error'>
</div>
This is just an example feel free to adjust anything, i removed some tags and stuff but you can re add them this is just to show you how to do
So the script checks if 2numbers have been entered if yes it checks if the first one is 2 if not it shows err message and reset input value else it writes good
Here is the fiddle
https://jsfiddle.net/qh7gwecc/3/
Upvotes: 1