Saturday 4 August 2012

Validation



validation for text box and allowed only characters
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Enter the Name");
return false;
}
var namePattern = /^[A-Za-z]{1,25}$/;
if( !namePattern.test(document.myForm.name.value))
  {

alert("Please enter a valid string. The only characters accepted are A - Z and a - z");
return false;
}

validation for text box and allowed only Numbers
function checkString1(text)
{
if(!isNaN(text))
{
return 1;
}
else
{
alert("Please enter a numbers only");
return 0;
}
}


var x=document.forms["myForm"]["age"].value;
if (x==null || x=="")
  {
alert("Enter the Age");
  return false;
}
if(checkString1(document.forms["myForm"]["age"].value)==false)
{
document.forms["myForm"]["age"].value="";
return false;
}


validation for Radio Button

var nSex = document.forms["myForm"]['gender'];
if (nSex[0].checked == false && nSex[1].checked == false)
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}

email validation

var x=document.forms["myForm"]["email"].value;      
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }


CheckBox Validation

var chks = document.getElementsByName('hobbies[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (!hasChecked)
{
alert("Please select at least one.");
chks[0].focus();
return false;
}

ListBox Validation

var listBoxSelection=document.getElementById("country").value;
  if(listBoxSelection==0)
{
  alert("Please select a Country");
  return false;
}

Select file or image validation

var f = document.getElementById("image").value;
if(f==0)
{
alert( "Select a photo");
return false;
}


Javascript for 6 characters minimum,one number,one uppercase valdation in password field

Password Regular Expression Pattern
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})


Description:
 
(               #  Start of group
  (?=.*\d)        #   must contains one digit from 0-9
  (?=.*[a-z])     #   must contains one lowercase characters
  (?=.*[A-Z])     #   must contains one uppercase characters
  (?=.*[@#$%])    #   must contains one special symbols in the list "@#$%"
              .   #     match anything with previous condition checking{6,20}    # length at least 6 characters and maximum of 20    
)                 # End of group





No comments:

Post a Comment