Fungsi validasi HTML Form – Javascript


Untuk dapat memakai fungsi validasi ini dibutuhkan beberapa fungsi tambahan seperti fungsi ucwords(), startsWith() dan isEmail(), sedangkan fungsi pemanggilnya adalah validasi(). Berikut source code javascriptnya :

function validasi(delimiter,elementId){
	var formElement;
	var jumlahArray;
	var i;
	var formName = "";
	var messageAlert = "";

	formElement = elementId.split(delimiter);

	for(i=0;i<formElement.length;i++){
		if(formElement[i].startsWith("email")){
			if(document.getElementById(formElement[i]).value == ""){
				formName = formElement[i];
				messageAlert = "Form Email masih kosong";
				break;
			}else if(!isEmail(document.getElementById(formElement[i]).value)){
				formName = formElement[i];
				messageAlert = "Format Email Anda kurang tepat";
				break;
			}
		}else if(document.getElementById(formElement[i]).value == ""){
			formName = formElement[i];
			messageAlert = 'Maaf, silahkan isi form '+ucwords(formName);
			break;
		}
	}

	if(formName != ""){
		document.getElementById(formName).focus();
		alert(messageAlert);
		return false;
	}else{
		return true;
	}
}

Diatas hanyalah fungsi pemanggil, untuk mendapatkan fungsi pendukungnya silahkan download source file aslinya disini. Untuk implementasi dari fungsi tersebut diatas silahkan lihat source berikut :

<form method="post" action="">
	<table border="0" cellpadding="1" cellspacing="1">
		<tr>
			<td width="15%">Nama Lengkap</td>
			<td align="left"><input type="text" name="nama" id="nama lengkap"></td>
		</tr>
		<tr>
			<td align="left">Email</td>
			<td align="left"><input type="text" name="email" id="email"></td>
		</tr>
		<tr>
			<td align="left">Alamat Lengkap</td>
			<td align="left"><textarea name="address" id="alamat"></textarea></td>
		</tr>
		<tr>
			<td align="left" style="border:0px;">&nbsp;</td>
			<td align="left" style="border:0px;">
				<input type="submit" name="register" onclick="return validasiDaftar(',','nama lengkap,email,alamat')" value="Daftar Sekarang">
			</td>
		</tr>
	</table>
</form>

One thought on “Fungsi validasi HTML Form – Javascript

Mari Berdiskusi Bersama

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