I have a text <input>
with maxlength="6"
but I want to check if the first 4 characters are numbers and the last 2 are letters.
I have this code:
$("input[id='post']").keyup(function count() {
//what goes here?
});
but I really don't know how to go on further.
I have a text <input>
with maxlength="6"
but I want to check if the first 4 characters are numbers and the last 2 are letters.
I have this code:
$("input[id='post']").keyup(function count() {
//what goes here?
});
but I really don't know how to go on further.
Share Improve this question edited Oct 7, 2013 at 16:03 CSᵠ 10.2k9 gold badges43 silver badges64 bronze badges asked Oct 7, 2013 at 10:06 FvOFvO 723 silver badges12 bronze badges 2-
try
keypress
instaed ofkeyup
– bhb Commented Oct 7, 2013 at 10:12 - 1 Define "numbers" and do you expect only latin letters?. – meze Commented Oct 7, 2013 at 10:12
4 Answers
Reset to default 4You can use RegEx to do this
$("input[id='post']").keyup(function count() {
var input = this.value;
var regex = new RegExp(/^[0-9]{4}[a-z]{2}$/i);
console.log(regex.test(input));
});
[0-9]{4}
- Checks for four digits between 0-9.
[a-z]{2}
- Checks for two letters between a-z. The i
flag at the end makes the check case-insensitive.
You can use regular expressions:
https://developer.mozilla/en/docs/Web/JavaScript/Guide/Regular_Expressions
Something like:
$("input[id='post']").keyup(function count() {
var valid = /^\d{4}[a-zA-Z]{2}$/.test(this.value);
});
so that valid
will be true
if the input matches your condition, and false
otherwise.
This will log Valid
to console if it matches the required pattern:
$('#post').keyup(function() {
if (/^\d{4}[a-zA-Z]{2}$/.test(this.value)) {
console.log("Valid");
}
});
You can use a regular expression like this ^[0-9]{4}[a-z]{2}$
and make a key up/down
function to use it
See this link from to test the usage
Demo Testing and regex explained