Javascript validate form before submit

Categorías: 

Etiquetas: 

Some functions to validate a form before submit

  • HTML form
<form name="example-form" method="post" action="">
  <div class="form-group ">
    <label for="Model[name]">Name</label>
    <input id="Model_name" name="Model[name]" class="form-control" type="text" placeholder="Name" value="">
  </div>
  <input type="submit" value="send" class="btn btn-primary">
</form>
  • Javascript functions
/**
 * Checks if a field is empty
 * @param {string} fieldName html label 'name'
 * @param {string} additionalText [optional] 
 * @returns {String}
 */
function validateRequireFieldByName(fieldName, additionalText)
{
    additionalText = typeof additionalText !== 'undefined' ? additionalText : '';
 
    var field = $('[name="' + fieldName + '"]');
    var fieldValue = field.val();
    var parent = field.parent();
 
    if (fieldValue) {
        parent.removeClass("has-error").addClass("has-success");
        return '';
    } else {
        padre.removeClass("has-success").addClass("has-error");
        var label = parent.children("label").text();
        return label + ' ' + additionalText + ' is required\n';
    }
}
  • Main function to validate before submit
$('#example-form').on('submit',function(event) {
    var formData = $(this).serializeArray();
    var errorMessage = '';
 
    for (var input in formData){
        var element = $('input[name="' + formData[input].name +'"]');
        var fieldName = element.attr('name');
 
        errorMessage += validateRequireFieldByName(fieldName);        
    }
 
    if (errorMessage !== '') {
        event.preventDefault();
        alert(msgError);
    }
 
});