How to validate a Text Field in PHP by using JavaScript

Today I am going to show you how to write a simple JavaScript function. The scenario is, by the time I click my submit button if there are empty text fields in the form, an alert message will display with the help of JavaScript.

Fist I will show my form interface.

Form
Figure 1

I am going to write the JavaScript for the onclick function of the Submit button. If the Username text box is empty, then it will display an alert message like below.

Alert
Figure 2

You have to include following code with in these tags;

<script type=”text/javascript”> … </script>

...

  function loginvalidation(){
	  if(document.login.textfieldUsername.value == ""){
		  alert("Username cannot be empty");
		  return (false);
	}else if(document.login.textfieldPassword.value == ""){
		alert("Password cannot be empty");
		return(false);
		}
  }

...

login is my form id, textfiledUsername is the id relevant to Username field and textfieldPassword is the other id. The most important thing is, you have to add the above written JavaScript in to the onclick function of the Submit button as follow.

...
input type="submit" name="buttonSubmit" id="buttonSubmit" value="Submit" onclick="javascript: return loginvalidation()"
...

That’s all about today’s post. Thank you 🙂

Advertisement

About AnujAroshA

Working as a Technical Lead. Specialized in iOS application development. A simple person :)
This entry was posted in Javascript, PHP examples. Bookmark the permalink.

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 )

Connecting to %s