...

View Full Version : Form field validation - characters 1 and 4



RichardH
11-07-2006, 05:51 PM
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>

Philip M
11-07-2006, 07:37 PM
<script language="JavaScript" type="text/javascript">
<!--
function Format(lstr){ // lstr is the variable passed to the function
if (/^[A][A-Z0-9][A-Z0-9][AB]$/i.test(lstr.value)) {
// match returns true, so proceed
}
else
{
// match returns false - retry or whatever??
}
}

You say that the field can have a maximum of four characters (what do you mean? Alpha characters? Alpha-numeric characters? Any character??) and the fourth character must be A or B. What if the field has only three characters or fewer?

The above regex requires a string of exactly four characters, the first must be A (or a), the next two can be A-Z, a-z or 0-9, the fourth chaarcter must be A or B (or a or b). If this is not exactly what you want please come back.

RichardH
11-07-2006, 08:17 PM
Thank you Philip, that's exactly what I needed and it works a treat.

Richard



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum