Skip to content

Instantly share code, notes, and snippets.

@devfred
Last active October 6, 2015 08:38
Show Gist options
  • Save devfred/2966803 to your computer and use it in GitHub Desktop.
Save devfred/2966803 to your computer and use it in GitHub Desktop.
javascript: Check inputs for empty strings
<form action="#action" method="get">
<label For="FirstName">First Name*</Label>
<input id="FirstName" Type="text" Name="FirstName" class="required" data-message="Please fill in First name"/>
<label For="LastName">Last Name*</Label>
<input id="LastName" name="LastName" class="required" data-message="Please fill in Last name"/>
<input Type="submit" name="send" />
</form>
(function($, undefined){
// cache form
var theForm = $('form');
/**
Xbrowser trim function
@function trim
@parameter {string} str
**/
var trim = function(str) {
str = str.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
};
/**
Function to check for empty form values
@function validateForm
@parameter {object} e
**/
var validateForm = function(e){
var invalid = [];
var message = "";
// find required fields
var requiredFields = theForm.find('.required');
// check that field values are not empty
requiredFields.each(function(){
var $elem = $(this);
// check curren elem value for empty string
var value = trim($elem.val());
if(value === ""){
e.preventDefault();
e.stopPropagation();
// push to invalid array
invalid.push($elem);
}
});
if (invalid.length){
// Build single message from each invalid message
$.each(invalid, function(){
message = message + this.attr('data-message') + '\n';
});
// notify user
alert(message);
}
};
// bind validate function to form submit event
theForm.bind('submit', validateForm);
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment