Wednesday, July 24, 2013

Simple JavaScript Required Field Validation

HTML Form:

Below is a simple HTML form with a textbox to be validated and a submit button. we need to fire the validation on submit button click if the Email textbox is empty.

<form id="htmlfeedback-form">
  <input type="text" name="email" id="htmlfeedback-input-email" style="width:88%"/>
  <input type="submit" id="htmlfeedback-submit" value="Send">


function validateEmpty(fld) {
                var error = "";

                if (fld.value.length == 0) {
           = 'pink';
           = 'red';
                    error = "The required field has not been filled in.\n"
                else {
           = 'White';
            return error;

Jquery Form Submit:

Below code submits the form using jquery and will fire the validation if the textbox is empty

 $("#htmlfeedback-form").submit(function(e) {
                    if (validateEmpty(document.getElementById("htmlfeedback-input-email"))=="") {
                    // Code if TextBox not empty


No comments:
Write comments
Recommended Posts × +