Javascript validation check


There ate two javascript validation function i have made.

First one check empty field using id. We may use field id by an array as bellow. This function check empty field and if found empty field then focus that field also. We may use here another condition like email, phone number check. I think this will be reduce line number of code and time also.
Example:
<form method=”post” action=”<?=$_SERVER[‘PHP_SELF’]?>” onSubmit=”return checkClientForm();”>
<input type=”text” name=”name” id=”name” value=”” tabindex=”1″ /><br />
<input type=”text” name=”title” id=”title” value=”” tabindex=”2″ /><br />
<input type=”text” name=”description” id=”description” value=”” tabindex=”3″ /><br />
<input type=”submit” name=”submit” value=”Save” tabindex=”4″ />
</form>

Second one check file type like image. We may use this function by onchange element. If the file type dose not match then this will give a alert and clear the field also.

Example:
<input type=”file” name=”image” id=”image” value=”” onchange=”checkPhoto()” />

<script language=”javascript” type=”text/javascript”>
function checkClientForm(){
var cont;
var allid = new Array(“name”,”title”,”description”); //you may add more
var msg;
for (var i=0; i<=allid.length-1; i++){
cont=document.getElementById(allid[i]).value;
if(cont.length==0){
alert(“You should fill the required fields properly”);
document.getElementById(allid[i]).focus();
return false;
}
}
return true;
}

function checkPhoto(){
if( (document.getElementById(‘image’).value.split(‘.’)[1]!=’jpg’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’jpeg’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’JPG’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’JPEG’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’png’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’PNG’)){ alert(“Sorry, This type of file is not allowed to upload.”); document.getElementById(‘image’).value=”; document.getElementById(‘image’).focus(); return false; }
}
</script>

Advertisements

3 thoughts on “Javascript validation check

  1. রানা ভাই,
    আপনাকে অনেক ধান্যবাদ । আপনার comment আমার অনেক ভাল লেগেছে ।আপনার ব্লগ আমার ভাল লাগে কারন আমি বাপ্যার গুলু সহজেই বুঝতে পারি।আসা করি আবার contact হবে।

    শামীম আহমেদ
    সি-এস-ই-০৫
    রাজশাহী প্রকৌশল ও প্রযুক্তি বিশ্ববিদ্যালয়
    রাজশাহী

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s