Friday, 22 January 2016

Form Validation

Limit minimum length
if (document.form1.password.value.length < 6)
{
alert("Please give a Password more than 5 characters");
                document.form1.password.focus();
                return false;

}
Confirm Password
if ((document.form1.pass.value) != (document.form1.r_pass.value))
{
                alert("Your password does not match");
                document.form1.r_pass.value == "";
                document.form1.r_pass.focus();
                return false;
            }
            return( true );


Restrict a field to accept Numeric
function isNumeric(elem, helperMsg){
  var numericExpression = /^[0-9]+$/;
  if(elem.value.match(numericExpression)){
  return true;
  }else{
  alert(helperMsg);
  elem.focus();
  return false;
  }
}

..............................................................
Complete Example
<script type='text/javascript'>
function isNumeric(elem, helperMsg){
  var numericExpression = /^[0-9]+$/;
  if(elem.value.match(numericExpression)){
  return true;
  }else{
  alert(helperMsg);
  elem.focus();
  return false;
  }
}
</script>

<form>
Numbers Only: <input type='text' id='numbers'/>
<input type='button'
  onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')"
  value='Check Field' />
</form>
Restrict a field to accept Alphabets
function isAlphabet(elem, helperMsg){
  var alphaExp = /^[a-zA-Z]+$/;
  if(elem.value.match(alphaExp)){
  return true;
  }else{
  alert(helperMsg);
  elem.focus();
  return false;
  }
}

COMPLETE EXAMPLE

<script type='text/javascript'>
function isAlphabet(elem, helperMsg){
  var alphaExp = /^[a-zA-Z]+$/;
  if(elem.value.match(alphaExp)){
  return true;
  }else{
  alert(helperMsg);
  elem.focus();
  return false;
  }
}
</script>
<form>
Letters Only: <input type='text' id='letters'/>
<input type='button'
  onclick="isAlphabet(document.getElementById('letters'), 'Letters Only Please')"
  value='Check Field' />
</form>

0 comments:

Post a Comment