Tuesday, February 13, 2007

Javascript: Proper case validation

I am just posting a Javascript sample which I created for answering a question in dotnetspider.

<html>
<head>
<title>Proper Case Validation -- Sample by Vadivel</title>
<script>
<!--

function ConvertToProperCase()
{
strTemp = document.form1.txtString.value
strTemp = strTemp.toLowerCase()

var test=""
var isFirstCharOfWord = 1

for (var intCount = 0; intCount < strTemp.length; intCount++)
{

var temp = strTemp.charAt(intCount)
if (isFirstCharOfWord == 1)
{
temp = temp.toUpperCase()
}

test = test + temp
if (temp == " ")
{
isFirstCharOfWord = 1
}
else isFirstCharOfWord = 0
}
document.form1.txtString.value = test
}
// -->
</script>
</head>

<body>

<form name=form1>
<input size=50 name=txtString>
<input type=button onClick=ConvertToProperCase() value="Convert It Now">
</form>

</body>
</html>

Update: I have tested it with IE 6.0 alone. May be for working in other browsers you need to do little bit of tweaking. For ex: need to put semi-colons at the end of each statements.

3 comments:

DotNet Guts (DNG) said...

After verifying javascript with javascript verifier i found no. of errors... even i would suggest you to run the same page with firefox and you find the same... so after removing error with jslint.com i found the valid equivalent javascript as under:

function ConvertToProperCase()
{
strTemp = document.form1.txtString.value;
strTemp = strTemp.toLowerCase();

var test="";
var isFirstCharOfWord = 1;

for (var intCount = 0; intCount < strTemp.length; intCount++)
{

var temp = strTemp.charAt(intCount);
if (isFirstCharOfWord == 1)
{
temp = temp.toUpperCase();
}

test = test + temp;
if (temp == " ")
{
isFirstCharOfWord = 1;
}
else
{
isFirstCharOfWord = 0;
}
}
document.form1.txtString.value = test;
}

sample said...

Nice Work !!

Lane Pemberton said...

How do you make it so certain words in a string are not affected by the function?