ShareThis

JavaScript Email Validation, Radio Button Validation

Here is a Javascript example for validate an email address and validate radio buttons on a form. For the radio buttons it will check that, one has selected and returns which one has selected.


function validateInputs()
{
errText = "";

uSignUpEmail = document.getElementById('txtSignUpEmail').value;
if ((uSignUpEmail.length <= 0) || (emailCheck(uSignUpEmail)==false))
{
errText = errText + '

Your Email address will be used as you site login please make sure that you have entered it correctly.

';

}

uRadioAge = frmUserSignUp.radioAge;
if(uRadioAge)
{
if(valRadioButton(uRadioAge)==null)
{
errText = errText + '

Please let us know if you are over 18.

';

valid = false;
}
}

document.getElementById('validationSummary').innerHTML = errText;
}


// Email Address Validation
function emailCheck(str)
{
var at="@";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (str.indexOf(at)==-1)
{
return false;
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
{
return false;
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
{
return false;
}
if (str.indexOf(at,(lat+1))!=-1)
{
return false;
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
{
return false;
}
if (str.indexOf(dot,(lat+2))==-1)
{
return false;
}
if (str.indexOf(" ")!=-1)
{
return false;
}
return true;
}


// Radio Button Validation
function valRadioButton(btn)
{
var cnt = -1;
for (var i=btn.length-1; i > -1; i--)
{
if (btn[i].checked)
{
cnt = i; i = -1;
}
}
if (cnt > -1)
{
return btn[cnt].value;
}
else
{
return null;
}
}

HTML Code

input name="txtSignUpEmail" type="text" class="formtextbox" id="txtSignUpEmail" />

I am 18 years of age or older
input name="radioAge" type="radio" value="true" id="radioAge1" />
Yes
input name="radioAge" type="radio" value="false" id="radioAge2" />
No

input name="Submit" id="Submit" type="image" onclick="return validateInputs();" src="Images/btSignup.jpg" width="111" height="31" />




0 comments: