ray9209
ray9209

Reputation: 388

Simplifying Form validation

I have a form with 5 input fields (4 text input, 1 checkbox) and I have written this code to handle missing information in the input fields. The code works fine but but it seems repetitive and inefficient. Is there a simpler way to write this code?

$("#main-form").on('submit', function(event) {

if (!$("#field1").val()) {
event.preventDefault();
$("#field1-error").html("Error!");
}
else
$("#field1-error").html("");

if (!$("#field2").val()) {
event.preventDefault();
$("#field2-error").html("Error");
}
else
$("#field2-error").html("");

if (!$("#field3").val()) {
event.preventDefault();
$("#field3-error").html("Error");
}
else
$("#field3").html("");

if (!$("#field4").val() && !$("#checkbox1").prop('checked')) {
event.preventDefault();                                       
$("#field4-error").html("Error");
}
else
$("#field4-error").html("");

});

Upvotes: 0

Views: 64

Answers (2)

Sean
Sean

Reputation: 427

If the function does the same thing on multiple similar fields, it is best to just write one function. I think every Javascript engineer at some point or another has banged their head against a wall trying to come up with a slicker way run form validations.

For this situation I would write the function and call it whenever I needed it. Try this:

$("#main-form").on('submit', function(event) {
  myValidations.contentsPresent('#field1', '#field1-error');//call the first field validaitions
  myValidations.contentsPresent('#field2', '#field2-error');//second
  //third 
  //etc
});

var myValidations = 
{
    contentsPresent: function(fieldId, errorId)
    {
        if (!$(fieldId).val()) {
            event.preventDefault();
            $(errorId).html("Error!");
        }       
        else
            $(errorId).html("");
        }
    },
    contentsPresentCheckBox: function(fieledId, checkboxId, errorId)
    { 
        if (!$(fieledId).val() && !$(checkboxId).prop('checked')) {
            event.preventDefault();                                       
            $(errorId).html("Error");
        }
        else
            $(errorId).html("");
        }
    }
}

Upvotes: 1

Mark Arciaga
Mark Arciaga

Reputation: 38

//Try this.

$(document).ready(function(){

    /** Form Validation */
    $("#formId").validate({
        rules: {
             field1:{ required: true },
             field2:{ required: true },
             field3:{ required: true },
             field4:{ required: true }
        },
        messages: {
             field1:{ required: 'Field1 is required!' },
             field2:{ required: 'Field2 is required!' },
             field3:{ required: 'Field3 is required!' },
             field4:{ required: 'Field4 is required!' }
        }

        // Submit function

});

// This is a simple jquery form validation but you need to include the jquery validation plugin. http://jqueryvalidation.org/

Upvotes: 0

Related Questions