Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Form field validation - characters 1 and 4

Status
Not open for further replies.

RichardH123

Programmer
Nov 10, 2005
2
GB
I am trying to validate a form field. The field can have a maximum of 4 characters. The first character is always the letter 'A', the fourth character can be either the letter 'A' or the letter 'B' but nothing else. I also need a mask on the field like this A _ _ _

I have this code, but I am now stuck. Any help with this is much appreciated.

<script language="JavaScript" type="text/javascript">
<!--
function Format(obj){
string='A _ _ _ '
val=obj.value.replace(/_/g,'');
val=val.replace(/A/g,'');
val=val.replace(/\s/g,'');
val1=''
for (zxc0=0;zxc0<val.length;zxc0++){
val1+=val.charAt(zxc0)+' ';
}
if (val1.length<0){
obj.value=val1+string.substring(val1.length,string.length);
}
else{
val2=val1.substring(0,0)+'A '+val1.substring(6,0);
obj.value=val2+string.substring(val2.length,string.length);
}
}

//-->
</script>
 
Maybe this will be a little more use to you... I've used simple structures to make the function easy to understand.

Code:
function maskFormat(data) {
	if (data != '' && data != null) {
		data = data.toUpperCase().split('');
	} else {
		data = [];
	}
	data[0] = 'A';
	if (data.length > 3) {
		if (!(data[3] == 'A' || data[3] == 'B')) {
			data[3] = '_';
		}
	} else {
		if (data.length == 1) data[1] = '_';
		if (data.length == 2) data[2] = '_';
		if (data.length == 3) data[3] = '_';
	}
	return data[0] + data[1] + data[2] + data[3];
}

You might call this using an onkeyup event on an input:
Code:
...
<input onkeyup="this.value=maskFormat(this.value);" maxlength="5" value=""/>
...

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Thanks Jeff

That's good thank you.

I have gone for this instead.

<script language="JavaScript" type="text/javascript">
<!--
function Format2(lstr){ // lstr is the variable passed to the function
if (/^[A][ ][A-Z0-9][ ][A-Z0-9][ ][AB][ ]$/i.test(lstr.value)){
lstr.value = lstr.value.toUpperCase();
}
else
{
lstr.value = "";
alert("That is not a valid code")
}
}
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--
function Format(obj){
string='A _ _ _ '
val=obj.value.replace(/_/g,'');
val=val.replace(/A/g,'');
val=val.replace(/\s/g,'');
val1=''
for (zxc0=0;zxc0<val.length;zxc0++){
val1+=val.charAt(zxc0)+' ';
}
if (val1.length<0){
obj.value=val1+string.substring(val1.length,string.length);
}
else{
val2=val1.substring(0,0)+'A '+val1.substring(6,0);
obj.value=val2+string.substring(val2.length,string.length);
}
}

//-->
</script>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top