Simple HTML Form Validation with JavaScript & JQuery

Some years ago, a new Javascript library came out called JQuery, which is very powerful and simplifies many common website and web application tasks. One very useful feature of JQuery is the validation of HTML forms. I developed a GeoSpatial web application with Microsoft ASP.NET and hosted on the Microsoft Azure Cloud, but is now inactive. The web application uses JQuery to validate html forms.

The source code for this web application is publicly viewable on my Azure DevOps source control account at:

GeoSpatial Web Application

The Locations view on this web application lets you enter the name of a location and the Latitude and Longitude of a location, and then when the form is submitted, a list of distances to locations in the Cocoa Beach, Florida area and Central Florida area is provided. This is a simple HTML form that is validated using JQuery.

Not that there are 2 different ways to validate HTML forms with JQuery, the old way is to do the validation with simple JQuery and no special libraries included, and the new way is to use a special library called VALIDATION that makes validating forms very simple and easy to do. In this blog post we will use the old method, and then at a later time in a different blog post, I will show how to use the new method.

Here is the HTML form in the Razor view Locations in the geospatial web application:

    <form method="post" id="FindDistancesForm" action="/Home/Locations">
        <hr />
        @Html.AntiForgeryToken()

        @* Location *@
        <div class="form-group">
            @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-3">
                @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @id = "Location", @maxlength = "100", @class = "form-control" } })
            </div>
        </div>

        @* Latitude *@
        <div class="form-group">
            @Html.LabelFor(model => model.Latitude, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-3">
                @Html.EditorFor(model => model.Latitude, new { htmlAttributes = new { @id = "Latitude", @maxlength = "50", @class = "form-control" } })
            </div>
        </div>

        @* Longitude *@
        <div class="form-group">
            @Html.LabelFor(model => model.Longitude, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-3">
                @Html.EditorFor(model => model.Longitude, new { htmlAttributes = new { @id = "Longitude", @maxlength = "50", @class = "form-control" } })
            </div>
        </div>

        @* Form Submit Button *@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button id="FindBTN" type="button" value="Find" class="btn btn-primary">Find Distances</button>
            </div>
        </div>

    </form>


Now, since we are going to validate the form with JQuery, and submit the form with JQuery also, we need to change the form so that it does not do a default submit when the submit button is clicked. This is what our submit button looks like before this change.

        @* Form Submit Button *@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button id="FindBTN" type="submit" value="Find" class="btn btn-primary">Find Distances</button>
            </div>
        </div>
        

Note that the button type is SUBMIT, that means when the button is clicked, the form will be submitted, and will be submitted regardless of any JQuery code that is run. That is the default form submit method. However, we need to change this so that the form does not do a default SUBMIT when clicked. We do this by changing the button TYPE from SUBMIT, to BUTTON, like in the following:

        @* Form Submit Button *@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button id="FindBTN" type="button" value="Find" class="btn btn-primary">Find Distances</button>
            </div>
        </div>
        

Now, after this change, the form will only be submitted after we tell the JQuery code to do the submit, and that will only happen after the JQuery validates the data inputted into the form as being correct data.

Since we are dealing with an ASP.NET MVC Web Application, we will have to create a SCRIPTS section at the bottom of the Locations view and include a JQuery opening statement like the following:

@* JQuery Code For Form Validation *@
@section Scripts {
    <script type="text/javascript">
        $(document).ready(function () {

            $("#FindBTN").click(function () {

            });
        });
    </script>
} 

Now, this code will run specific JQuery code when the FindBTN button is clicked, after the button is clicked, we want to check the data in the form elements of the form to make sure that it is correct data.

First we will add the following code to setup our validation section, a statement to clear out any previous error messages, and including a boolean variable to be a sentinel whether the form will be submitted or not, and also simple vars for the form elements themselves.

The word ERROR represents a CSS class we are going to use in our generated error messages. It starts with a dot to mean that it is a class in the form element,  to reference a form element by its ID, we use the # sign, a class can apply to one or more HTML elements, but an ID can only apply to one HTML element.

  	// clear previous errors
	$(".error").remove();

	// sentinel value whether or not to submit form
	var formValidated = true;

	// vars for our form elements
	var location = $("#Location");
	var latitude = $("#Latitude");
	var longitude = $("#Longitude");
  

Next we will validate the Location form element to make sure that data was entered into it, and is not an empty string, and if there is an error, we set the boolean sentinel var to FALSE, we will then add some HTML after the element as the error message using the AFTER method. We will use a SPAN html tag to display the error message, with a class of error, and also a class of TEXT-DANGER, which is a Bootstrap css class with red text. This will produce the error message on our html form when the error occurs. We do this with the following:

	// Location
	if (location.val().trim() == "") {
 		formValidated = false;
		location.after("<span class='error text-danger'>Location Required</span>");
	}
  

Next we will validate that a Latitude coordinate was entered in the form, is a proper number, and is in the valid range of -90 to +90. If not, we generate error messages and set the sentinel var to FALSE. With the following:

	// Latitude - test for empty string
 	if (latitude.val().trim() == "") {
		formValidated = false;
		latitude.after("<span class='error text-danger'>Latitude Required</span>");
	}

	// Latitude - test for valid number
	else if (isNaN(latitude.val())) {
		formValidated = false;
		latitude.after("<span class='error text-danger'>Latitude Not a Number</span>");
	}

	// Latitude - test for valid range, -90 to +90
	else if ((latitude.val() > 90) || (latitude.val() < -90)) {
		formValidated = false;
		latitude.after("<span class='error text-danger'>" +
			"Latitude Invalid Range, Less than - 90 or Greater than + 90" +
			"</span>");
	}

Next we will validate the Longitude coordinate was entered in the form, is a proper number, and is in the valid range of -180 to +180. If not, we generate error messages and set the sentinel var to false, like in the following:

	// Longitude - test for empty string
	if (longitude.val().trim() == "") {
		formValidated = false;
		longitude.after("<span class='error text-danger'>Longitude Required</span>");
	}

 	// Longitude - test for valid number
	else if (isNaN(longitude.val())) { 
		formValidated = false;
		longitude.after("<span class='error text-danger'>Longitude Not a Number</span>");
	}

	// Longitude - test for valid range, -180 to +180
	else if ((longitude.val() > 180) || (longitude.val() < -180)) { 
		formValidated = false;
		longitude.after("<span class='error text-danger'>" +
			"Longitude Invalid Range, Less than - 180 or Greater than + 180" +
			"</span>");
	}

Now our form validation is complete, if no error was encountered, the sentinel var FORMVALIDATED will still be TRUE. If errors were encountered, error messages will be shown on the web page and the sentinel var will be FALSE.

If the formValidated var is still true, we clear out the previous error messages, and we then submit the form with the following JQuery:

	// submit form if no errors
	if (formValidated) {
		$(".error").remove();
		$("#FindDistancesForm").submit();
	}

That is all that is needed to validate the Locations form with JQuery, it is infinitely more simple to do than with normal Javascript. In my next blog post about JQuery, I will show how to use the VALIDATION library in JQuery to validate HTML forms. Also a simple thing to do.

For those who wish to try out and learn Unix, there is a NetBSD Unix shell account available from SDF at http://sdf.org for $9 every 3 months. Also, a free OpenBSD Unix shell account is available on https://tilde.institute. There is free Linux offerings on the internet as well. A free Ubuntu Linux shell account is available at https://tilde.team. Many Linux versions are available as free downloads on the internet as well.

To see my Curriculum Vitae, go to Michael G Workman CV

To see my projects on Azure DevOps, go to https://dev.azure.com/AbionTechnology/

To see my Posts and Answers on Stack Overflow, go to Michael G. Workman on Stack Overflow

 If you have any questions about C,  C++,  JavaScript,  Microsoft C# .NET,  Microsoft Azure Cloud, Unix, Linux, and/or Mobile Apps, please feel free to contact me by email at:

michael.g.workman@outlook.com

Popular Posts