Jquery Form validation using object - javascript

I working with form validation. My code is working fine but whenever I click on send button validations showing multiple time. And here I want to add radio button, checkbox, select according to my code. How should I add these other fields? I tried my level best but couldn't achieve it.
Can anyone help me to add this to other fields?
Below is my code:
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
};
this.validate = function() {
var errorCount = 0;
this.form.find("input, textarea").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if (validation){
if (!validation.reg.test($(field).val())){
errorCount++;
handleError($(field), validation.error);
}
}
})
return errorCount == 0;
};
};
$(function(){
$("form#test").on("submit", function(event){
//event.preventDefault();
return new Validator(this).validate(); // "this" here refers to the form
})
})
<style type="text/css">
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="name">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email"/>
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
</form>

Please check this codepen:
https://codepen.io/creativedev/pen/BVNXYE
I have added this line
$err_msg.find('.error').remove();
Updated code:
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
};
this.validate = function() {
var errorCount = 0;
this.form.find("input, textarea").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if (validation){
if (!validation.reg.test($(field).val())){
errorCount++;
handleError($(field), validation.error);
}
}
})
return errorCount == 0;
};
};
$(function(){
$("form#test").on("submit", function(event){
//event.preventDefault();
return new Validator(this).validate(); // "this" here refers to the form
})
})

<script>
jQuery(function()
{
jQuery("#test").validate({
rules:
{
"firstname":
{
required: true
},
"lastname":
{
required: true
},
"email":
{
required: true
},
"message":
{
required: true
}
}
});
});

whenever I click on send button validations showing multiple time
$err_msg.empty(); /* add this cleanup old errors */
error.appendTo($err_msg);

Related

Problem with my textarea in the form on my website

I'm new here :)
I've been trying to built a form with 2 inputs and one textarea. When I check the inputs, everything goes fine, but the problem occurs when I try to submit my form. Even though the textarea field is not empty, the function doesn't change my border into green color, and the text in below doesn't dissaper.
On the other hand, when I put an eventlistener while checking inputs - form closes, after filling textarea with any letter.
I cannot think of any solution, I would like an eventlistener to work exactly the same as it works on inputs.
I hope you understand my problem, I attach my code to show you my point of view.
Hope I get some answers from you! :)
Thanks!
// Formularz - the form
const form = document.querySelector('form');
const yourName = document.getElementById('name');
const email = document.getElementById('email');
const msg = document.getElementById('message');
form.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
})
yourName.addEventListener('input', () => {
checkInputs();
})
email.addEventListener('input', () => {
checkInputs();
})
function checkInputs() {
const yourNameValue = yourName.value.trim();
const emailValue = email.value.trim();
const msgValue = msg.value.trim();
if(yourNameValue === '') {
setErrorFor(yourName, 'Name is required')
}
else {
setSuccesFor(yourName);
}
if(emailValue === "") {
setErrorFor(email, 'Email is required')
}
else if(!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid')
}
else {
setSuccesFor(email)
}
if (msgValue === "") {
setTextError(msg, 'Message is required')
}
else {
setTextSuccess(msg)
}
// zamykanie formularza - closing the form
if (yourNameValue && emailValue && msgValue) {
form.classList.add('close');
}
}
function setTextError(textarea, message) { // funkcja odpowiedzialna za textarea - function responsible for textarea
const formControl = textarea.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setTextSuccess(textarea) {
const formControl = textarea.parentElement;
formControl.className = 'form-control success';
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small')
// add error message inside small
small.innerText = message;
// add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^\S+#\S+\.\S+$/.test(email);
}
.form-parent {
background-color: lightblue;
color: white;
}
textarea {
resize: none;
padding: 5px;
}
form {
display: block;
margin-top: 20px;
padding: 20px 20px 0;
}
input, label, textarea {
width: 100%;
font-family: Roboto, sans-serif;
}
.form-control label {
display: inline-block;
margin-bottom: 5px;
color: black;
}
.form-control input {
display: block;
padding: 5px;
}
.form-control {
position: relative;
margin-bottom: 10px;
padding-bottom: 20px;
}
#submit {
padding: 10px 30px;
margin:10px 0 20px;
background-color: lightblue;
color: black;
border: solid white 1px;
font-family: Roboto, sans-serif;
font-size: 1rem;
}
small {
font-family: Roboto, sans-serif;
margin-top: 5px;
visibility: hidden;
color: rgb(182, 19, 19);
position: absolute;
bottom: 0;
left: 0;
}
/* input check */
.form-control.success input {
border: 2px solid green;
}
.form-control.error input {
border: 2px solid rgb(182, 19, 19);
}
.form-control.error textarea {
border: 2px solid rgb(182, 19, 19);
}
/* textarea check */
.form-control.success textarea {
border: 2px solid green;
}
.form-control.error small {
visibility: visible;
}
/* zamykanie formularza */ - closing the form
form.close {
visibility: hidden;
}
<div class="form-parent">
<form action="/" method="get">
<div class="form-control">
<label for="name">Name</label>
<input id="name" name="name" type="text">
<small></small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="email" type="email">
<small></small>
</div>
<div class="form-control">
<label for="message">Message</label>
<textarea id="message" cols="10" rows="10"></textarea>
<small></small>
</div>
<button id="submit" type="submit">Submit</button>
</form>
</div>
the form never gets submitted, and the close is added whenever all three fields are filled (you might add textarea minimum characters check)... The problem seems to be the submitting. Try this:
add input listener for textarea
when setting close, also return true to submit check method, which will indicate that the form is valid, and then submit the form programmatically from there
change submit button's submit id to submit-btn in HTML and CSS, to allow form.submit method
const form = document.querySelector('form');
const yourName = document.getElementById('name');
const email = document.getElementById('email');
const msg = document.getElementById('message');
form.addEventListener('submit', (e) => {
e.preventDefault();
const check = checkInputs();
if (check) form.submit();
})
yourName.addEventListener('input', () => {
checkInputs();
})
email.addEventListener('input', () => {
checkInputs();
})
msg.addEventListener('input', () => {
checkInputs();
})
function checkInputs() {
const yourNameValue = yourName.value.trim();
const emailValue = email.value.trim();
const msgValue = msg.value.trim();
if (yourNameValue === '') {
setErrorFor(yourName, 'Name is required')
} else {
setSuccesFor(yourName);
}
if (emailValue === "") {
setErrorFor(email, 'Email is required')
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Email is not valid')
} else {
setSuccesFor(email)
}
if (msgValue === "") {
setTextError(msg, 'Message is required')
} else {
setTextSuccess(msg)
}
// zamykanie formularza - closing the form
if (yourNameValue && emailValue && msgValue) {
form.classList.add('close');
return true;
}
}
function setTextError(textarea, message) { // funkcja odpowiedzialna za textarea - function responsible for textarea
const formControl = textarea.parentElement;
const small = formControl.querySelector('small');
small.innerText = message;
formControl.className = 'form-control error';
}
function setTextSuccess(textarea) {
const formControl = textarea.parentElement;
formControl.className = 'form-control success';
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small')
// add error message inside small
small.innerText = message;
// add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^\S+#\S+\.\S+$/.test(email);
}
.form-parent {
background-color: lightblue;
color: white;
}
textarea {
resize: none;
padding: 5px;
}
form {
display: block;
margin-top: 20px;
padding: 20px 20px 0;
}
input,
label,
textarea {
width: 100%;
font-family: Roboto, sans-serif;
}
.form-control label {
display: inline-block;
margin-bottom: 5px;
color: black;
}
.form-control input {
display: block;
padding: 5px;
}
.form-control {
position: relative;
margin-bottom: 10px;
padding-bottom: 20px;
}
#submit-btn {
padding: 10px 30px;
margin: 10px 0 20px;
background-color: lightblue;
color: black;
border: solid white 1px;
font-family: Roboto, sans-serif;
font-size: 1rem;
}
small {
font-family: Roboto, sans-serif;
margin-top: 5px;
visibility: hidden;
color: rgb(182, 19, 19);
position: absolute;
bottom: 0;
left: 0;
}
/* input check */
.form-control.success input {
border: 2px solid green;
}
.form-control.error input {
border: 2px solid rgb(182, 19, 19);
}
.form-control.error textarea {
border: 2px solid rgb(182, 19, 19);
}
/* textarea check */
.form-control.success textarea {
border: 2px solid green;
}
.form-control.error small {
visibility: visible;
}
/* zamykanie formularza */
- closing the form form.close {
visibility: hidden;
}
<div class="form-parent">
<form action="/" method="get">
<div class="form-control">
<label for="name">Name</label>
<input id="name" name="name" type="text">
<small></small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="email" type="email">
<small></small>
</div>
<div class="form-control">
<label for="message">Message</label>
<textarea id="message" cols="10" rows="10"></textarea>
<small></small>
</div>
<button id="submit-btn" type="submit">Submit</button>
</form>
</div>

Form validation error messages without moving input fields

I need help with form validation. I would like for the error messages to not move the entire input field when they show up. This way, I can put them on my #media queries without them moving down and taking up another section below the ones they belong on. I have tried to add margins beneath the input fields but that doesn't work, it just increases the space between the input fields. Is there a work around here? I have just learned this JS yesterday.
Here is my codepen:
https://codepen.io/drxl/pen/WNpVQaQ
<form action="" method="POST" id="contact-form" class="contact">
<div class="name-form">
<label for="name">Your Name</label>
<input id="name" type="text" placeholder=" Your name..." required>
</div>
<div class="email-form">
<label for="email">Your Email</label>
<input id="email" type="email" placeholder=" Your email..." required>
</div>
<div class="contact__txtarea">
<label for="text">Message</label>
<textarea class="textarea" id="text" placeholder=" Your message here..." required></textarea>
</div>
<div class="btn">
<input class="contact-section__btn" type="submit" value="Send Message" required>
</div>
</form>
label {
display: none;
font-size: 1px;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
-webkit-transition: "color 9999s ease-out, background-color 9999s ease-out";
-webkit-transition-delay: 9999s;
}
.contact input,
.contact textarea {
margin: .5rem;
font-weight: 1000;
font-family: "Roboto", sans-serif;
font-size: 1.1rem;
}
.name-form label,
.email-form label,
.contact__textarea label {
display: none;
}
input[type="text"],
[type="email"],
textarea {
background-color: rgb(223, 198, 182, 0.875);
border-color: rgb(201, 83, 5);
width: 550px;
height: 40px;
-webkit-box-shadow: rgb(36, 36, 36) 10px 10px 10px;
box-shadow: rgb(36, 36, 36) 10px 10px 10px;
}
::-webkit-input-placeholder {
color: black;
}
::-moz-placeholder {
color: black;
}
:-ms-input-placeholder {
color: black;
}
::-ms-input-placeholder {
color: black;
}
::placeholder {
color: black;
}
.name-form,
.email-form,
.contact__txtarea {
margin-bottom: 20px;
}
.contact__txtarea label,
.textarea {
width: 550px;
height: 300px;
vertical-align: top;
}
.error-message {
color: red;
font-size: 1rem;
}
.contact-section__btn {
padding: 12px 52px;
background: rgb(201, 83, 5);
border: none;
color: white;
font-size: 1rem;
margin-right: 200rem;
-webkit-appearance: none;
}
.contact-section__btn:hover,
.contact-section__btn:focus {
background-color: rgb(209, 179, 124, 0.7);
opacity: .7;
color: black;
cursor: pointer;
transform: scale(0.85);
transition: ease .45s;
margin: 12px;
}
(function() {
let form = document.querySelector('#contact-form');
let nameInput = document.querySelector('#name');
let emailInput = document.querySelector('#email');
let textAreaInput = document.querySelector('#text');
function showErrorMessage(input, message) {
let container = input.parentElement;
let error = container.querySelector('.error-message');
if (error) {
container.removeChild(error);
}
if (message) {
let error = document.createElement('div')
error.classList.add('error-message');
error.innerText = message;
container.appendChild(error);
}
}
function validateName() {
let value = nameInput.value;
if(!value) {
showErrorMessage(nameInput, 'Name is a required field.');
return false;
}
showErrorMessage(nameInput, null);
return true;
}
function validateEmail() {
let value = emailInput.value;
if (!value) {
showErrorMessage(emailInput, 'Email is a required field.');
return false;
}
if (value.indexOf('#') === -1) {
showErrorMessage(emailInput, 'You must enter a valid email address.');
return false;
}
showErrorMessage(emailInput, null);
return true;
}
function validateTextArea() {
let value = textAreaInput.value;
if (!value) {
showErrorMessage(textAreaInput, 'You must enter a message.');
return false;
}
showErrorMessage(textAreaInput, null);
return true;
}
function validateForm() {
let isValidName = validateName;
let isValidEmail = validateEmail;
let isValidTextArea = validateTextArea;
return isValidName && isValidEmail && isValidTextArea;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
if (validateForm()) {
alert('Success!');
}
});
nameInput.addEventListener('input', validateName);
emailInput.addEventListener('input', validateEmail);
textAreaInput.addEventListener('input', validateTextArea);
})();

Validate form input fields using jquery

I'm working on form validation. Everything is working fine what I actually want is I want to add some more input fields like checkbox, radio button, select and textarea, upload file and like so into the form I want them to be validated as well.
I got the email input error working but it is not working correctly as it should validate the email first and then it should remove the error message but it is removing the error message just after entering few characters.
I want the phone number to be validated. Like the user should enter 10 numeric digits that is in India if in another country that will differ I am a bit confused how to do it.
I want a success message to pop up when all the fields are correctly validated as they should. what I tried is this:
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
I want all the fields to be cleared when all the validations are done and the success message is sent.
Can anyone point me in the right direction?
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
};
this.validate = function() {
var errorCount = 0;
this.form.find("input, textarea").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if (validation) {
if (!validation.reg.test($(field).val())) {
errorCount++;
handleError($(field), validation.error);
}
}
})
return errorCount == 0;
};
};
$(function() {
$("form#test").on("submit", function(event) {
//event.preventDefault();
return new Validator(this).validate(); // "this" here refers to the form
})
})
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email" />
</div>
<div>
<label for="phone">phone</label>
<input type="number" name="phone" id="phone" data-validation="phone" />
</div>
<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" data-validation="gender" />
<input type="radio" name="gender" value="female" data-validation="gender">
</div>
<div>
<label>select</label>
<input type="checkbox" name="checkbox" id="checkbox1" value="demo1" data-validation="checkbox" />
<input type="checkbox" name="checkbox" id="checkbox2" value="demo2" data-validation="checkbox" />
<input type="checkbox" name="checkbox" id="checkbox3" value="demo3" ata-validation="checkbox" />
</div>
<select data-validation="selectOption">
<option value="">Select any option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<div>
<label>Upload:</label>
<input type="file" name="file" id="file" data-validation="file" />
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
Please feel free to clear your doubts before you invest your time answering the question.
Here is the working code:
https://jsfiddle.net/bhumi/o2gxgz9r/47570/
I have changed selector to use id
You need to use loop in handle error:
var Validator = function(form) {
this.form = $(form);
var Elements = {
name: {
selector: $('input[type=text]'),
reg: /^[a-zA-Z]{2,20}$/
},
email: {
selector: $('input[type=email]'),
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i
},
message: {
selector: $('textarea'),
reg: /^\s+$/
}
};
var handleError = function(element, message, v1) {
if (v1.selector.length > 1) {
var ss = v1.selector;
$(ss).each(function(i, v) {
$(v).removeClass('input-error');
if($(v).val() == ''){
$(v).addClass('input-error');
var $err_msg = $(v).parent('div');
if($(v).parent('div').find('.error').length == 0) {
var error = $('<div class="error"></div>').text(message);
}else{
$(v).parent('div').find('.error').text('');
var error = $(v).parent('div').find('.error').text(message);
$(this).siblings('.error').show();
}
error.appendTo($err_msg);
}else{
$(v).siblings('.error').text('')
}
$(v).keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
});
} else {
element.addClass('input-error');
var $err_msg = element.parent('div');
if(element.parent('div').find('.error').length == 0) {
var error = $('<div class="error"></div>').text(message);
}else{
element.parent('div').find('.error').text('');
var error = element.parent('div').find('.error').text(message);
$(this).siblings('.error').show();
}
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
}
};
this.validate = function() {
this.form.submit(function(e) {
for (var i in Elements) {
var type = i;
var validation = Elements[i];
switch (type) {
case 'name':
if (!validation.reg.test(validation.selector.val())) {
handleError(validation.selector, 'Not a valid name.', validation);
}
break;
case 'email':
if (!validation.reg.test(validation.selector.val())) {
handleError(validation.selector, 'Not a valid e-mail address.', validation);
}
break;
case 'message':
if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
handleError(validation.selector, 'Message field cannot be empty.', validation);
}
break;
default:
break;
}
}
e.preventDefault();
});
};
};
var validator = new Validator('#test');
validator.validate();
I hope this is what you were trying to achieve. This took longer than expected but I tried to achieve it. This whole form is custom form. You could have used the existing plugins to achieve it. Any which ways it took much time to figure it out. Consider the question as most of things are working, ignore if something's not what you want.
$(document).ready(function() {
/* contact form validation */
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z ]{2,20}$/,
require: true,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
gender: {
error: "gender is required",
},
selectOption: {
error: "this field is required",
required: true
}
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
console.log(element);
element.on('keypress change', function() {
$(error).fadeOut(1000, function() {
console.log(element);
element.removeClass('input-error');
});
});
};
/* Select Option */
this.validate = function() {
var errorCount = 0;
this.form.find("select").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if ($(field).val() == "") {
errorCount++;
handleError($(field), validation.error);
}
});
this.form.find("input, textarea").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if (validation !== undefined) {
var re = new RegExp(validation.reg);
if (validation) {
if (!re.test($(field).val())) {
errorCount++;
handleError($(field), validation.error);
}
}
}
})
/* Radio button */
var radioList = $('input:radio');
var radioNameList = new Array();
var radioUniqueNameList = new Array();
var notCompleted = 0;
for (var i = 0; i < radioList.length; i++) {
radioNameList.push(radioList[i].name);
}
radioUniqueNameList = jQuery.unique(radioNameList);
console.log(radioUniqueNameList);
for (var i = 0; i < radioUniqueNameList.length; i++) {
var field = $('#' + radioUniqueNameList[i]);
var type = field.data("validation");
var validation = Elements[type];
if ($('input[name=' + type + ']:checked', '#test').val() == undefined) {
errorCount++;
handleError($(field), validation.error);
}
}
return errorCount == 0;
};
};
/* Submit form*/
$(function() {
$("form#test").on('submit', function(e) {
var NoErrors = new Validator(this).validate();
if (NoErrors == true) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function() {
// AJAX request finished, handle the results and error msg
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input[type!="submit"], textarea').val('').removeClass('error');
}
});
}
return false;
})
})
});
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email" />
</div>
<div>
<label for="phone">phone</label>
<input type="number" name="phone" id="phone" data-validation="phone" />
</div>
<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" data-validation="gender" />
<input type="radio" name="gender" value="female" data-validation="gender">
</div>
<select data-validation="selectOption">
<option value="">Select any option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>

Why the input fields are cleared by pressing the <button>

I have a classic message form, which does not need a function to sent a messages. She created only for analyzing all input fields on content, and if the input fields are clear - script must show the tooltips info for the customer.
The problem is when I click on the button with pre-written fields, content in the fields are gone.
var fromWho = document.querySelector('[name="from"]');
var pass = document.querySelector('[name="pass"]');
var repeatPass = document.querySelector('[name="repeatPass"]');
var message = document.querySelector('[name="message"]');
var button = document.querySelector('button');
function onClick(e) {
if (fromWho.value = '') {
var helpFrom = document.createElement('span');
helpFrom.innerHTML = 'Please, insert sender data!';
helpFrom.style.color = 'red';
};
if (pass.value = '') {
var helpPass = document.createElement('span');
helpPass.innerHTML = 'Please, insert password!';
helpPass.style.color = 'red';
};
if (repeatPass.value != pass.value) {
var helpRepeatPass = document.createElement('span');
helpRepeatPass.innerHTML = 'Passwords do not match!';
helpRepeatPass.style.color = 'red';
};
if (message.value = '') {
var helpMessage = document.createElement('span');
helpMessage.innerHTML = 'Wrie your message!';
helpMessage.style.color = 'red';
};
console.log(fromWho.value);
}
button.addEventListener( 'click', onClick );
body {
font-family: 'Arial', sans-serif;
font-size: 12px;
}
p {
display: inline-block;
margin: 0 0 5px 0;
}
input, select {
float: right;
}
input[type="button"] {
float: left;
}
textarea {
width: 288px;
height: 114px;
margin: 0px;
resize: vertical;
}
.message-wrap {
width: 294px;
height: auto;
}
.message-wrap__from {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__password {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__repeatPassword {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__toWhom {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__message {
margin-bottom: 5px;
}
.message-wrap__message > p {
display: block;
}
.toWhom__select {
width: 160.5px;
height: 22px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<div class="message-wrap">
<div class="message-wrap__from">
<p>From</p>
<input type="text" name="from">
</div>
<div class="message-wrap__password">
<p>Your password</p>
<input type="password" name="pass">
</div>
<div class="message-wrap__repeatPassword">
<p>Repeate password</p>
<input type="password" name="repeatPass">
</div>
<div class="message-wrap__toWhom">
<p>To</p>
<select class="toWhom__select">
<option value="1">Logistic sector</option>
<option value="2">Financial sector</option>
<option value="3">Director</option>
</select>
</div>
<div class="message-wrap__message">
<p>Message:</p>
<textarea name="message" name="message"></textarea>
</div>
<button>Check</button>
</div>
<script>
</script>
</body>
</html>
if conditions need to be checked with a == or a ===. = will give a new value to the variable and this explains the behaviour.
if (fromWho.value == '') {
var helpFrom = document.createElement('span');
helpFrom.innerHTML = 'Please, insert sender data!';
helpFrom.style.color = 'red';
};
...
your example:
var fromWho = document.querySelector('[name="from"]');
var pass = document.querySelector('[name="pass"]');
var repeatPass = document.querySelector('[name="repeatPass"]');
var message = document.querySelector('[name="message"]');
var button = document.querySelector('button');
function onClick(e) {
if (fromWho.value == '') {
var helpFrom = document.createElement('span');
helpFrom.innerHTML = 'Please, insert sender data!';
helpFrom.style.color = 'red';
};
if (pass.value == '') {
var helpPass = document.createElement('span');
helpPass.innerHTML = 'Please, insert password!';
helpPass.style.color = 'red';
};
if (repeatPass.value != pass.value) {
var helpRepeatPass = document.createElement('span');
helpRepeatPass.innerHTML = 'Passwords do not match!';
helpRepeatPass.style.color = 'red';
};
if (message.value == '') {
var helpMessage = document.createElement('span');
helpMessage.innerHTML = 'Wrie your message!';
helpMessage.style.color = 'red';
};
console.log(fromWho.value);
}
button.addEventListener( 'click', onClick );
body {
font-family: 'Arial', sans-serif;
font-size: 12px;
}
p {
display: inline-block;
margin: 0 0 5px 0;
}
input, select {
float: right;
}
input[type="button"] {
float: left;
}
textarea {
width: 288px;
height: 114px;
margin: 0px;
resize: vertical;
}
.message-wrap {
width: 294px;
height: auto;
}
.message-wrap__from {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__password {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__repeatPassword {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__toWhom {
margin-bottom: 5px;
height: 22px;
}
.message-wrap__message {
margin-bottom: 5px;
}
.message-wrap__message > p {
display: block;
}
.toWhom__select {
width: 160.5px;
height: 22px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<div class="message-wrap">
<div class="message-wrap__from">
<p>From</p>
<input type="text" name="from">
</div>
<div class="message-wrap__password">
<p>Your password</p>
<input type="password" name="pass">
</div>
<div class="message-wrap__repeatPassword">
<p>Repeate password</p>
<input type="password" name="repeatPass">
</div>
<div class="message-wrap__toWhom">
<p>To</p>
<select class="toWhom__select">
<option value="1">Logistic sector</option>
<option value="2">Financial sector</option>
<option value="3">Director</option>
</select>
</div>
<div class="message-wrap__message">
<p>Message:</p>
<textarea name="message" name="message"></textarea>
</div>
<button>Check</button>
</div>
<script>
</script>
</body>
</html>

Error placement using tooltipster and jQuery form validation plugins?

I use jQuery form validation plugin This one to validate my form and tooltipster to show errors messages.
The code working with no problems to validate the form and show errors the only problem appear when I show some hidden form elements after the error messages shows up.
So if I submit the form after showing the hidden elements (which is showed dynamically related to user choices ) there is no problem in error message placement,
but if the form submitted and the user choose to show the hidden elements after the error message appear the error position goes wrong.
HTML
<form id="eway" method="post" action="" ENCTYPE="multipart/form-data">
<div class="roww">
<select name="txtAmount" id="txtAmount" class="inputfield select" >
<option value="Amount">Select Amount</option>
<option value="5">$5</option>
<option value="10">$10</option>
<option value="15">$15</option>
<option value="25">$25</option>
<option value="50">$50</option>
<option value="70">$75</option>
<option value="100">$100</option>
<option value="Custom">Custom Amount</option>
</select>
</div>
<div id="customAmount" style="display: none;">
<div class="roww">
<input name="txtCustomAmount" type="text" id="txtCustomAmount" class="inputfield" placeholder="Please enter amount more than $1"/>
</div>
</div>
<div class="roww">
<input name="txtLastName" type="text" id="txtLastName" class="inputfield" placeholder="Please enter your last name"/> </div>
<div class="roww"><input name="txtMobileNumber" type="text" id="txtMobileNumber" class="inputfield" placeholder="Please enter your mobile number"/></div>
<input type="submit" name="btnProcess" value="Process Transaction" id="btnProcess" class="go backcolr"/>
<form>
CSS
<style>
.cont
{
/*width:400px; height:470px; float:left; */
}
.roww
{
width:445px; height:auto; float:left; margin:5px 0;
}
.firts
{
width:180px; height:30px; float:left; font-weight:bold;
}
.second
{
width:210px; height:30px; float:left;
}
. firts span
{
width:5px; height:25px; float:left; font-weight:bold; color:#F00
}
.showerror {border:1px solid #CE2726; padding:10px 15px; background:#FDE8E7; margin:5px 0 15px 0px; width:auto; color:#CE2726; ont-family: 'Ubuntu',sans-serif; font-size: 16px; font-weight: normal;}
.showsuccess {border:1px solid #ACDBAD; padding:10px 15px; background:#ECFAE3; margin:5px 0 15px 0px; width:auto; color:#4F8A10; ont-family: 'Ubuntu',sans-serif; font-size: 16px; font-weight: normal;}
.go {
border: medium none;
border-radius: 3px 3px 3px 3px;
color: #FFFFFF;
cursor: pointer;
font-family: 'Ubuntu',sans-serif;
font-size: 14px;
font-weight: bold;
padding: 6px 10px;
margin:0 0 0 0;
float:right;
}
.inputfield {
border: 1px solid #CBCBCB;
border-radius: 3px 3px 3px 3px;
box-shadow: 1px 1px 4px #E5E4E4 inset;
color: #666666;
float: left;
height: 32px;
line-height: 32px;
margin-bottom: 15px;
padding: 0 15px;
width: 240px;
}
.select { padding:6px 10px; width: 270px;}
.clear { clear:both;}
</style>
AND JS
$("#txtAmount").change(function(){
var val = $(this).val();
if(val == 'Custom'){
$("#customAmount").fadeIn();
}else{
$("#customAmount").fadeOut();
}
});
$('#txtAmount').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right'
});
$('#eway input[type="text"]').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right'
});
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg != value;
}, "Value must not equal arg.");
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#eway").validate({
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
rules: {
txtLastName: "required",
txtMobileNumber: "required",
txtAmount: {
valueNotEquals: "Amount"
}
},
messages: {
txtLastName: "Please enter your lastname",
txtMobileNumber: "Please enter a valid mobile number",
txtAmount: "please choose donation amount"
},
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
async: false,
dataType: 'json',
beforeSend : function (){
$('#loading').show();
},
success: function(response) {
var status = response.status;
var message = response.message;
$('#loading').hide();
if(status == 1){
$('#error').hide();
$('#result').show();
$('#result').html(message);
resetForm($('#eway'));
}else{
$('#result').hide();
$('#error').show();
$('#error').html(message);
}
}
});
}
});
}
}
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
$('#eway').submit(function(e) {
e.preventDefault();
});
also this the jsfiddle.net Link
you need to invoke tooltipster to reposition when the #textAmount changes. below you can have a look at the last three line I added. here is the fiddle http://jsfiddle.net/B7XYz/11/
$("#txtAmount").change(function(){
var val = $(this).val();
if(val == 'Custom'){
$("#customAmount").fadeIn();
}else{
$("#customAmount").fadeOut();
}
$(".roww").children().each(function(){
$(this).tooltipster("reposition");
});
});

Categories

Resources