Textbox to allow 3 letters & 4 numbers

Hi,
I need some javascript code that can restrict input to a textbox to only allow the following):
         -first 3 characters can be only A to Z (both lower & upper caps), or can also have either    of the characters: - (hiphen) and ' (single quote)
         -next 4 characters can be only integers from 0 to 9
         -nothing else is allowed, not even spaces.
Thanks in advance
ARC_UMAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

shadow77Commented:
Use the regular expression
^[a-zA-Z]{3}[-']\d{4}$
ddayx10Commented:
I wrote this up then there was an outage and I couldn't post it. This should help:
HTML:
		<input id="txtBox" type="text" maxlength="7" />
		<input type="button" value="Validate" onclick="validateMe();" />

Javascript:
    <script type="text/javascript">
    function validateMe()
    {
		var pattern = /[a-zA-Z]{3}[0-9]{4}/;
		var txtBox = document.getElementById('txtBox');
		
		if(txtBox.value.match(pattern) == null)
		{ alert('wrong-entry'); }
		else
		{ alert('correct-entry'); }
    }
    </script>

Open in new window

shadow77Commented:
Don't forget to put ^ at the beginning, $ at the end and [-'] in the middle.

Use my pattern and ddayx10's code.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

ddayx10Commented:
Ahhhh I see I didn't read carefully enough, good catch!
Regular Expressions make my head hurt! :)
käµfm³d 👽Commented:
Maybe I'm misinterpreting the requirement, but the description to me indicates the pattern should be as below--although I think it's a toss-up between this and what was already posted  :)
^[a-zA-Z'-]{3}\d{4}$

Open in new window

shadow77Commented:
You may be right.  The author should clarify.

Are the - or ' optional?
Do they replace one or more of the letters?
Only one?  Up to three?
Do they separate the letters from the numbers?
Is the number of characters always 8? 7? Can it vary?
Shahan AyyubSenior Software EngineerCommented:
Try this one:

^[A-Z|a-z]{3}['|-][0-9]{4}$

This should do it.
käµfm³d 👽Commented:
@Shahan_Developer

How is that any different than shadow77's original post? Besides, the pipe ( | ) inside of a bracket is redundant...   a bracket expression implicity means an OR between all characters.
shadow77Commented:
kaufmed's post (four back) throws the whole question open.  He points out that there are multiple potential interpretations of the original problem, so we need ARC_UM to clarify the requirements.

The pipe inside the brackets is worse than redundant.  It will be treated as one of the characters that can be matched at that point (ie, match ' or | or -).
käµfm³d 👽Commented:
>> The pipe inside the brackets is worse than redundant.  It will be treated as one of the characters that can be matched...

Agreed.
Shahan AyyubSenior Software EngineerCommented:
@ kaufmed

I donot follow any expert for my post. I just read the question and try to solve. If my post would be the repeated one the author will reject it.

käµfm³d 👽Commented:
Don't quite understand your logic, but hey, if it works for you, then I guess all is well.   :)
ARC_UMAuthor Commented:
input can only be seven characters of whic:
           -first 3 can be lower & upper caps A to Z or - or '
           -last  4 can only be digits from 0 to 9
which regular expression is correct?Thanks
shadow77Commented:
kaufmed is correct (nine comments up).
ARC_UMAuthor Commented:
doesn't look like it's working.
the reg expr is not to allow users to input anything apart from the pattern & if they type something else it will keep giving them warning msgs. Can you help please?

<script type="text/javascript">

    function validateMe()
    {
                var pattern = ^[a-zA-Z'-]{3}\d{4}$;
                var student= document.getElementById('student');
                
                if(student.value.match(pattern) == null)
                	alert('wrong-entry');
                else
                	alert('correct-entry');
    }


</script>

Open in new window

shadow77Commented:
I'm rusty on my JavaScript.

I think you need to quote the pattern and the hyphen needs to come first in the brackets so it isn't interpreted as part of a range (like [a-z]).
    var pattern = '^[-a-zA-Z']{3}\d{4}$';
ARC_UMAuthor Commented:
The expr is still not working.
shadow77Commented:
Try
    var pattern = /^[-a-zA-Z']{3}\d{4}$/;
shadow77Commented:
You may need to escape the '
    var pattern = /^[-a-zA-Z\']{3}\d{4}$/;

Sorry, my Javascript is rusty.
ARC_UMAuthor Commented:
i think i got the reg expression correct but it's the condition that's not working.
it always shows wrong entry & doesn't delete the wrong entered character
shadow77Commented:
How about something like this?
<script type="text/javascript">
    function validateMe()
    {
	var re = new RegExp(/^[-a-zA-Z\']{3}\d{4}$/);
        var student= document.getElementById('student');
                
        if (student.value.search(re) < 0) {
            alert('wrong-entry');
        else
            alert('correct-entry');
    }
</script>

Open in new window

ARC_UMAuthor Commented:
it doesn't work
shadow77Commented:
Can you post the test strings you are using?

Have you confirmed that student.value holds the strings you want to check?  Perhaps you could add it to your alerts temporarily.

I don't have a way to test this right now so I need to ask you.
ddayx10Commented:
I tested it this way and believe it is working at least the regular expression part anyway. First 3 chars allowed are:
[Any letter plus ' (single quote) and - (hyphen)]

Last 4 characters allowed are:
[numeric only]

I read your post from 3 above:
>>>the reg expr is not to allow users to input anything apart from the pattern & if they type something else it will keep giving them warning msgs.<<<

I am concerned this means you are looking for a key-stroke solution. If the user presses any key other than the one's selected then an error is fired/displayed. That is a horse of a different color although the regular expression may still come in handy. Is this what you are looking for?

If so I'm too tired to take that on now (going home). I apologize for my part of the misunderstanding. I can see how the words in your original post ("Restrict Input to a textbox") could mean restrict via keystroke. I just went with standard validation tactics of "restrict form from posting". My bad I should have clarified it with you before posting anything.

Good news is it's nothing new, heck a quick search or two will find several working solutions.
1) Attach event on focus to catch keypress
2) Only allow some keys when lengh < 4
3) Only allow other keys when length > 4

Ahhh I'm feelin guilty so I'll get it close. The following works with the button, or you can ignore the button and try just using with keypress. There are other (and better) ways to do this likely, but...
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function validateMe()
    {
		//var pattern = /[a-zA-Z]{3}[0-9]{4}/;
		var pattern = /^[-'a-zA-Z]{3}\d{4}$/;
		var txtBox = document.getElementById('txtBox');
		
		if(txtBox.value.match(pattern) == null)
		{ alert('wrong-entry'); }
		else
		{ alert('correct-entry'); }
    }
    
    function textChecker(e)
    {
		var pattern1 = /[-'a-zA-Z]/;
		var pattern2 = /\d/;
		var txtBox = document.getElementById('txtBox');
		var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
		var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
				
		if((txtBox.value.length + 1) <= 3 && String.fromCharCode(unicode).match(pattern1) == null)
		{
			alert('user-error1');
			return false;
		}
		else if((txtBox.value.length + 1) >= 4 && String.fromCharCode(unicode).match(pattern2) == null)
		{
			alert('user-error2');
			return false;
		}
		else
		{ return true; }
	}

    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<input id="txtBox" type="text" maxlength="7" onfocus="document.onkeypress=textChecker;" onblur="return false;" />
		<input type="button" value="Validate" onclick="validateMe();" />
    </div>
    </form>
</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ARC_UMAuthor Commented:
I have used:
Li-0000
O'C9999
no matter what i type, previously it was saying they wre all incorrect & now its doesn't do anything & lets me type
shadow77Commented:
I tested those two strings against the pattern and both matched.  I also made several small changes and the changed strings all failed.

There must be something wrong in the function.

Are you sure that student.value holds the strings you want to check?  Might it be student.text?

Maybe you should try
        if (re.test(student.value))
            alert('correct-entry');
        else
            alert('wrong-entry');

You should also look at what ddayx10 has posted.
käµfm³d 👽Commented:
In response to post #30888868, the hyphen can be placed either after the opening bracket or before the closing bracket when including hyphen inside of a character class  :)

It would be helpful to all if you could post the relevant code (event  handlers and scripts) you are using. Saying that something doesn't work without providing insight as to how you have implemented your code makes our job rather difficult  :)
shadow77Commented:
@kaufmed

You are correct.  I was mistaken.  I also tested this version
    ^[a-zA-Z-']{3}\d{4}$
and it worked too.  Apparently, the re processor recognizes that a hyphen following A-Z cannot be part of a range.
ARC_UMAuthor Commented:
@ ddayx10: almost exactly what i was looking for. should have made clear about the keystroke part.
thanks heaps
ARC_UMAuthor Commented:
@ ddayx10: hi, when i move from that textbox to the next one, it still shows error when i start typing on the new textbox although the previous ones input is correct
ARC_UMAuthor Commented:
@ ddayx10: hi, when i move from that textbox to the next one, it still shows error when i start typing on the new textbox although the previous ones input is correct
ARC_UMAuthor Commented:
@ ddayx10:
it checks but then the users cant write in other parts of teh folder as the error msg keeps coming.
can you plz help?
ddayx10Commented:
Oh man I feel aweful. Once I saw it was resolved I took this off monitoring. There is no way to turn it back on. If you still need help of course I will look at it again. I'll check back in the next few days and see if you respond. Again really sorry. I dont check the emails too often because I get too many....
ARC_UMAuthor Commented:
the code you posted works to some extent. it checks the user input and doesn't let a user to put in anything else. but when the user move to the next field, even though they've entered this field correctly -- the check wouldn't let the user to move to teh next field and keeps coming back here with error msg.
it would be great if you can help. thanks
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.