patternjavascriptMinor
Validating HTML Form
Viewed 0 times
formhtmlvalidating
Problem
I am trying to create a simple validation for forms. I am almost there, but there are few bugs and optimization errors that I am really struggling with. I'm looking for advice on how to make this function simpler and more understandable.
```
var errorMessage = {
required: "This field can not be empty",
email: "Please enter a valid email address",
number: "Please only enter numbers in this field",
min: "This field should be minimum ",
max: "This field should be maximum ",
date: "Please use the date format outlined above"
};
var $form = $("#contactForm");
var $formInputs = $("#contactForm input");
var $formTextareas = $("#contactForm textarea");
var $formSelects = $("#contactForm select");
var currentRadioSet = "";
$form.submit(function(event) {
event.preventDefault();
if (submitValidate()) {
var $el = $(this);
$submit = $el.find('button[id="submit"]');
$inputs = $el.find('input, textarea, select, label');
$.post($el.attr('action'), $form.serialize(), function(data) {
$('span.error').remove();
if (data) {
$submit.text('Sent. Thank You!');
$submit.add($inputs).addClass('disabled').prop('disabled', true);
} else {
$submit.after('Failed to send the message, please try again later.');
$submit.text('Try Again');
}
});
}
});
$formInputs.keyup(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formTextareas.keyup(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formTextareas.blur(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formInputs.blur(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
```
var errorMessage = {
required: "This field can not be empty",
email: "Please enter a valid email address",
number: "Please only enter numbers in this field",
min: "This field should be minimum ",
max: "This field should be maximum ",
date: "Please use the date format outlined above"
};
var $form = $("#contactForm");
var $formInputs = $("#contactForm input");
var $formTextareas = $("#contactForm textarea");
var $formSelects = $("#contactForm select");
var currentRadioSet = "";
$form.submit(function(event) {
event.preventDefault();
if (submitValidate()) {
var $el = $(this);
$submit = $el.find('button[id="submit"]');
$inputs = $el.find('input, textarea, select, label');
$.post($el.attr('action'), $form.serialize(), function(data) {
$('span.error').remove();
if (data) {
$submit.text('Sent. Thank You!');
$submit.add($inputs).addClass('disabled').prop('disabled', true);
} else {
$submit.after('Failed to send the message, please try again later.');
$submit.text('Try Again');
}
});
}
});
$formInputs.keyup(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formTextareas.keyup(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formTextareas.blur(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
checkForClasses($el);
});
$formInputs.blur(function() {
var $el = $(this);
if (!$el.hasClass("required")) {
resetSingleErrorMessage($el);
}
Solution
From a once over:
- Function names in JavaScript should only start with a capital if they are constructors, so
Numberis no good, since it returns a boolean, I would call itisNumber()
- I would put a
"use strict";after$(document).ready(function () {
if (!$.trim($element.val()) == "") {should be
if ($.trim($element.val()) != "") { ( put the ! in the comparison ).$submit,currentRadioSet,minValandmaxValwere not declared withvar
- From a design perspective, it does not seem right that your validation rules manage errors and can reset error messages, in my mind, that should be done elsewhere (
checkForClasses?), this will reduce a lot copy of paste code
- For
MinimumandMaximum, I would advise to get and set the minimum/maximum throught the$().data()mechanism instead of classnames and regexes.
- In
checkForClassesyou already dovar $element = $(element);and then in each validation function you do againvar $element = $(element);, that is overkill.
- I would only check for minimum and maximum if the
Numberclass is present
- Use either single or double quotes for strings, dont mix, ideally use single quotes
- In
validate()you can simply
return !$('.error').length;- Also, you are again doing
var $element = $(this);invalidate():D
- Please use jshint.com to self review your code, a lot of this feedback comes from there.
Context
StackExchange Code Review Q#41321, answer score: 6
Revisions (0)
No revisions yet.