I am new to jQuery, so I am trying to create my own form validation. AJAX submission was fine, but the validation itself is killing me.
The concept is this:
- The user clicks the submit button - 'beautify me'.
- If the one (or all) of the three required fields (
#name-input
,#email-input
,#phone-input
) are not filled in, than a error class (.validation-error
) should be added to the one, which is not filled. And, the whole thing should immediately scroll to#validation-fail-msg
which is displayed if error occurred (by default this message is hidden).
I am attaching a codepen with my "creation", so you might help if there is a chance. Thank you in advance guys.
http://codepen.io/anon/pen/oxjZav
<div class="b-form-wrap">
<p id="validation-fail-msg">Please, fill in the missing fields.</p>
<form novalidate id="feedback-form">
<div class="b-form-box">
<p class="form-box__text form-box__text_no-pad">What's your name?<sup class="form-box__sup">*</sup></p>
<input type="text" name="name" maxlength="30" required id="name-input" class="form-box__input-field">
<p class="form-box__text">What's your phone number?<sup class="form-box__sup">*</sup></p>
<input type="text" name="phone" maxlength="30" required id="phone-input" class="form-box__input-field">
<p class="form-box__text">What's your email?<sup class="form-box__sup">*</sup></p>
<input type="text" name="email" maxlength="50" required id="email-input" class="form-box__input-field">
</div>
<div class="b-form-box b-form-box_left-mrg">
<p class="form-box__text form-box__text_no-pad">How can I help you?</p>
<textarea name="text" class="form-box__input-field form-box__input-field_textarea"></textarea>
</div>
<button class="form-box__button">Beautify me</button>
<p id="validation-success-msg">Thanx, I'll contact you very soon.</p>
</form>
function feedback_validate() {
var result = true;
var f_names = ["#name-input", "#email-input", "#phone-input"];
var el;
f_names.forEach(function(item) {
el = $(item);
if (el.val() == "") {
result = false;
el.addClass("validation-error");
} else {
el.removeClass("validation-error");
}
});
if (result) {
$("#validation-fail-msg").hide();
} else {
$("#validation-fail-msg").show();
}
return result;
}