Validation on form submit - javascript

The span's innerHTML change depends on AJAX. If the span's innerHTML is <img src="images/not-available.png">, then submit should return false.
HTML:
<form onsubmit="return validateemail()">
<span id= "message"><img src="images/not-available.png"></span>
<button id='submit' name="submit" type='submit'>Submit</button>
</form>
JS:
function validateemail()
{
var munx = document.getElementById("message").innerHTML;
var muny = '<img src="images/not-available.png">';
if (munx == muny)
{
alert ("Email id is already Exist");
return false;
}
}
I tried this code, but it doesn't work.

You can use jQuery Validation Plugin (http://jqueryvalidation.org/validate/) in your project. This is standard form validation that you can use in diffrent way.
for example:
$(".selector").validate({
invalidHandler: function(event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
});
example of ajax: Submits the form via Ajax when valid.
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});

You are validating it wrong.
see this:
<span id= "message"><img src="images/not-available.png"></span>
and now see this:
var muny = '<img src="images/not-available.png"/>';
can you notice the extra "/" character in second one i.e just before img closing bracket. Thats causing the problem.
So replace with this one:
var muny = '<img src="images/not-available.png">';

Related

Implementing jQuery AJAX from within Javascript

I used a tutorial from css-tricks to help me with HTML5 Constraint Validation for my application's client-side validation. I would like to introduce an AJAX script that submits the form to prevent reloading the page (as the form is displayed in a modal pop-up that I don't want closing on submit.)
From what I have gathered online, it seems the best way to do this is to use jQuery. However, the validation script is written in regular ol' Javascript.
I'm kind of confused as to how to implement this within my validation script so that I don't need to make another http request to a separate js file (not even sure if that's an option, as I kind of need it to work seamlessly with the existing script). Do I just call jQuery inside the existing script to prevent conflicts (as shown below?) Do I need to wrap the entire script in the ready event?
Currently, I'm not sure why this isn't working. The form still submits and reloads the page, so it seems to be ignoring the Ajax submit function.
The following includes the form markup from its PHP class and the form.validate.js file used for validation and ajax:
function copyTxtVal(bf) {
if(bf.samecheck.checked == true) {
bf.contact_name_first.value = bf.cpap_sup_name_first.value;
bf.contact_name_last.value = bf.cpap_sup_name_last.value;
} else {
bf.contact_name_first.value = '';
bf.contact_name_last.value = '';
}
}
// Add the novalidate attribute when the JS loads
var forms = document.querySelectorAll('.validate');
for (var i = 0; i < forms.length; i++) {
forms[i].setAttribute('novalidate', true);
}
// Validate the field
var hasError = function (field) {
// Don't validate submits, buttons, file and reset inputs, and disabled fields
if(field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') return;
// Get Validity
var validity = field.validity;
// Get valid, return null
if(validity.valid) return;
// If field is required and empty
if (validity.valueMissing) return 'Please fill out this field.';
// If not the right type
if (validity.typeMismatch) {
if(field.type === 'email') return 'Please enter an email address.';
if(field.type === 'url') return 'Please enter a URL.';
}
// If too short
if (validity.tooShort) return 'Please lengthen this text to ' + field.getAttribute('minLength') + ' characters or more. You are currently using ' + field.value.length + ' characters.';
// If too long
if (validity.tooLong) return 'Please short this text to no more than ' + field.getAttribute('maxLength') + ' characters. You are currently using ' + field.value.length + ' characters.';
// If number input isn't a number
if (validity.badInput) return 'Please enter a number.';
// If a number value doesn't match the step interval
if (validity.stepMismatch) return 'Please select a valid value.';
// If a number field is over the max
if (validity.rangeOverflow) return 'Please select a smaller value.';
// If a number field is below the min
if (validity.rangeUnderflow) return 'Please select a larger value.';
// If pattern doesn't match
if (validity.patternMismatch) {
// If pattern info is included, return custom error
if (field.hasAttribute('title')) return field.getAttribute('title');
// Otherwise, generic error
return 'Please match the requested format.';
}
// If all else fails, return a generic catchall error
return 'The value you entered for this field is invalid.';
};
var showError = function(field, error){
// Add error class to field
field.classList.add('error');
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if error message field already exists
// If not, create one
var message = field.form.querySelector('.error-message#error-for-' + id );
if (!message) {
message = document.createElement('div');
message.className = 'error-message';
message.id = 'error-for-' + id;
field.parentNode.insertBefore( message, field.nextSibling );
}
// Add ARIA role to the field
field.setAttribute('aria-describedby', 'error-for-' + id);
// Update error message
message.innerHTML = error;
// Show error message
message.style.display = 'block';
message.style.visibility = 'visible';
}
var removeError = function(field) {
// Remove the error message
// Remove error class to field
field.classList.remove('error');
// Remove ARIA role from the field
field.removeAttribute('aria-describedby');
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if an error message is in the DOM
var message = field.form.querySelector('.error-message#error-for-' + id + '');
if (!message) return;
// If so, hide it
message.innerHTML = '';
message.style.display = 'none';
message.style.visibility = 'hidden';
};
//Listen to all blur events
document.addEventListener('blur', function (event) {
// Only run if field is in a form to be validated by our custom script
if (!event.target.form.classList.contains('validate')) return;
// Validate field
var error = hasError(event.target);
// If there's an error, show it
if(error){
showError(event.target, error);
return;
}
//Otherwise, remove any existing error msg
removeError(event.target);
}, true);
// Check all fields on submit
document.addEventListener('submit', function (event) {
// Only run on forms flagged for validation
if (!event.target.classList.contains('validate')) return;
// Get all of the form elements
var fields = event.target.elements;
// Validate each field
// Store the first field with an error to a variable so we can bring it into focus later
var error, hasErrors;
for (var i = 0; i < fields.length; i++) {
error = hasError(fields[i]);
if (error) {
showError(fields[i], error);
if (!hasErrors) {
hasErrors = fields[i];
}
}
}
// If there are errors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
}
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else {
(function($){
var form = $('#cpapsupform');
var formMessages = $('#cpap-form-messages');
// Is this line below necessary if I've done this in the normal js above?
$(form).submit(function(event){
event.preventDefault();
// Serialize Form Data
var formData = $(form).serialize();
//Submit the form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#cpap_sup_name_first').val('');
$('#cpap_sup_name_last').val('');
$('#contact_name_first').val('');
$('#contact_name_last').val('');
$('#cpap_contact_email').val('');
$('#cpap_contact_phone').val('');
$('#cpap_patient_dob').val('');
$('#cpap_patient_zip').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('An error occured and your message could not be sent.');
}
});
});
})(jQuery);
}
}, false);
Here is the form markup (excerpted from the php form class I am using):
<?php
<div id="cpap-form-area">
<div id="cpap-form-messages"></div>
<div class="cpap-form-greet">
<p>Some text goes here.</p>
</div>
<form method="POST" action="" id="cpapsupform" class="validate" enctype="multipart/form-data" >
<fieldset>
<legend>Patient Name</legend>
<div class="p-firstname">
<label for="cpap_sup_name_first">First Name:</label>
<input type="text" size="50" name="cpap_sup_name_first" id="cpap_sup_name_first" value="<?php echo $display['cpap_sup_name_first']; ?>" required />
</div>
<div class="p-lastname">
<label for="cpap_sup_name_last">Last Name:</label>
<input type="text" size="50" name="cpap_sup_name_last" id="cpap_sup_name_last" value="<?php echo $display['cpap_sup_name_last']; ?>" required />
</div>
</fieldset>
<fieldset>
<legend>Point of Contact</legend>
<div class="samename">
<div class="cpap_input_alt">
<input id="samecheck" type="checkbox" name="samecheck" onchange="copyTxtVal(this.form);">
</div>
<label for="samecheck">Use same as above</label>
</div>
<div class="c-firstname">
<label for="contact_name_first">First Name:</label>
<input type="text" size="50" name="contact_name_first" id="contact_name_first" value="<?php echo $display['contact_name_first']; ?>" required />
</div>
<div class="c-lastname">
<label for="contact_name_last">Last Name:</label>
<input type="text" size="50" name="contact_name_last" id="contact_name_last" value="<?php echo $display['contact_name_last']; ?>" required />
</div>
</fieldset>
<fieldset>
<legend>Contact Details</legend>
<div class="cpap-email-contact">
<label for="cpap_contact_email">Email:</label>
<input type="email" name="cpap_contact_email" id="cpap_contact_email" value="<?php echo $display['cpap_contact_email']; ?>" title="The domain portion of the email after '#' is invalid." pattern="^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,})+$" required />
</div>
<div class="cpap-tel-contact">
<label for="cpap_contact_phone">Phone:<br /><span class="tiny-txt">(10 digits; no spaces)</span></label>
<input type="text" maxlength="10" name="cpap_contact_phone" id="cpap_contact_phone" value="<?php echo $display['cpap_contact_phone']; ?>" pattern="\d{10}" required />
</div>
</fieldset>
<fieldset>
<legend>Patient Date of Birth</legend>
<div class="cpap-dob">
<label for="cpap_patient_dob">Birthdate: <br /><span class="tiny-txt">(MM/DD/YYYY)</span></label>
<input type="text" name="cpap_patient_dob" id="cpap_patient_dob" value="<?php echo $display['cpap_patient_dob']; ?>" title="Your date looks incorrect, or it doesn't match the required format." max-length="10" pattern="((0[1-9])|(1[0-2]))/(([0-2]\d)|([3][01]))/((19|20)\d{2})" required ></input>
</div>
</fieldset>
<fieldset>
<legend>Address Info</legend>
<div class="cpap-zip">
<label for="cpap_patient_zip">Patient Zipcode:<br /><span class="tiny-txt">(first 5 digits only)</span></label>
<input type="text" maxlength="5" name="cpap_patient_zip" id="cpap_patient_zip" value="<?php echo $display['cpap_patient_zip']; ?>" required ></input>
</div>
</fieldset>
<button type="submit" id="cpapAjaxButton" name="cpapAjaxButton">Submit Request</button>
<p class="form-msg">All fields must be completed</p>
<div class="clearfix"></div>
<?php wp_nonce_field('submit_cpap_form','nonce_field_for_submit_cpap_form'); ?>
</form>
</div>
First, you do have a syntax error in that you are missing the opening curly brace of your else branch right here:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else (function($){
It should be:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else { (function($){
And, to avoid these kinds of errors, good indentation and formatting of code goes a long way, so really, this would be the best way to write it:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else {
(function($) {
Now, to you main point. As long as you have referenced the JQuery library prior to your code needing to use it, you just go ahead and use JQuery when and where you need to. If you need some page initialization work done, then yes, a "document ready" function should be passed into the JQuery object. But, apart from that, you can leverage JQuery whenever you need to so the self-invoking function you have inside of your else branch is redundant - - if code execution enters that branch, you don't invoke JQuery again, you just use it.
Also, you start off with:
document.addEventListener('submit', function (event) {
But, the document object doesn't have a submit event. The event listener should be set up on the form element that is going to be submitted.
You also have some unnecessary variables and in a couple of cases, you set your variables equal to JQuery objects, but then passed those objects into the JQuery object again later as if they were regular DOM objects.
Here is your cleaned up code. Check the comments carefully for what changes were made and why. Also, this is the best we can do with answers since you didn't provide the hasError and showError functions and your HTML as well.
// The document object doesn't get submitted, the form does.
// Also this sytax finds every form that has the "validate" class,
// so there is no need to test for that in the callback function
$("form.validate").on('submit', function (event) {
// Get all of the form elements
var fields = event.target.elements;
// Always initialize your variables. Set them to null if you don't know the value to use yet
// Also, the "error" and "hasError" variables are not needed. You'll see why in a couple of lines down.
var hasErrors = null;
for (var i = 0; i < fields.length; i++) {
// I'm assuming you have a working "hasError" function that returns a boolean
// So, just take that return value and make that the basis for the if condition -- no
// need to store it just to test it on the next line.
if (hasError(fields[i])) {
// I'm assuming you have a working "showError" function. If we've entered into this
// branch of the code, we know that "hasError" returned true, so we can just pass that
// directly into the "showError" function instead of the "error" variable that we've
// now gotten rid of.
showError(fields[i], true);
// No need to test here. There is an error.
hasErrors = fields[i];
}
}
// If there are errors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
} else {
// You don't need a self-invoking function here. Just write the code that should execute
// It is a common convention to name variables that store references to JQuery objects
// with a leading $ to distinguish them as such and not regular DOM objects
var $form = $('#cpapsupform');
var $formMessages = $('#cpap-form-messages');
// Submit the form via AJAX
$.ajax({
type: 'POST',
url: $form.attr('action'), // $form is already a JQuery object, don't pass it to JQuery again
data: $form.serialize() // <-- You had semi-colon here, which you shouldn't have
}).done(function(response) {
// $formMessages is already a JQuery object, don't pass it to JQuery again
$formMessages.removeClass('error');
$formMessages.addClass('success');
// Set the message text.
$formMessages.text(response);
// Just use the DOM form.reset() method here instead of resetting each form field
$form[0].reset();
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$formMessages.removeClass('success');
$formMessages.addClass('error');
// Set the message text.
if (data.responseText !== '') {
$formMessages.text(data.responseText);
} else {
$formMessages.text('An error occured and your message could not be sent.');
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" class="validate">
<input type="text" id="name">
<input type="submit">
</form>
<form action="#" method="GET">
<input type="text" id="name">
<input type="submit">
</form>
jQuery IS Javascript, so of course you can use them together. I think your problem might lie in you not properly bracketing your else statement:
else { (function($){ // was missing brace after 'else'
var form = $('#cpapsupform');
var formMessages = $('#cpap-form-messages');
....
})(jQuery);
}//closing else brace

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

If/Else statement doesn't run inside function

I am trying to validate some input fields. More specifically, the number always has to be positive.
EDIT: JS code
$(document).ready(function($) {
$('.error-message').hide();
function priceCheck() {
$('input[class="price"]').each(function() {
priceValue = $(this).val();
console.log(priceValue); //only runs until here and seems it exists the function then
if (priceValue <= 0) {
evt.preventDefault();
return false;
} else {
}
});
}
//POST FORM
$("#offerInquiry").on('valid.fndtn.abide', function(evt) {
//prevent the default behaviour for the submit event
// Serialize standard form fields:
var formData = $(this).serializeArray();
var checked = $("#terms").is(":checked");
priceCheck();
if (checked == false) {
$('.error-message-container').empty();
$('.error-message-container').append("<%= pdo.translate("
checkBox.isObligatory ") %>");
$('.error-message').show();
$('.bid-error').css("display", "block");
evt.preventDefault();
return false;
} else {
loading();
$.post("/inquiry.do?action=offer&ajax=1", formData,
function(data) {
window.top.location.href = data.redirectPage;
});
}
return false;
});
});
I have written a function that I separately call on form submit. But it only runs until the console log. Why is the if else statement not executed?
You are using evt.preventDefault() but you didn't capture the event in evt.
For example, you could try this instead: add the evt parameter to the priceCheck function, and then pass evt to that function when you call it, like this: priceCheck(evt)
HOWEVER, you do not need to use preventDefault here. You can simply return a boolean value from priceCheck and use that in your submit handler.
You also you had a couple errors with string concatentation. $('.error-message-container').append("<%= pdo.translate(" checkBox.isObligatory ") %>"); was missing the + to concat those strings together . You can view errors like this in the Console tab of your JavaScript debugger. (UPDATE This is JSP injection, but it may not work the way you are trying to use it here. The server function pdo.translate will only execute once, on the server side, and cannot be called via client script... but it can emit client script. Focus on solving other problems first, then come back to this one.)
Finally, you were reading string values and comparing them to numbers. I used parseFloat() to convert those values from the input fields into numbers.
Here is the fixed code.
$(document).ready(function($) {
$('.error-message').hide();
function priceCheck() {
var priceValid = true; // innocent until proven guilty
$('input[class="price"]').each(function() {
priceValue = parseFloat($(this).val()) || 0;
if (priceValue <= 0) {
priceValid = false;
return false;
}
});
return priceValid;
}
$("form").on("submit", function() {
$("#offerInquiry").trigger('valid.fndtn.abide');
});
//POST FORM
$("#offerInquiry").on('valid.fndtn.abide', function(evt) {
//prevent the default behaviour for the submit event
// Serialize standard form fields:
var formData = $(this).serializeArray();
var checked = $("#terms").is(":checked");
var priceValid = priceCheck();
if (priceValid) {
$('.error-message').hide();
if (checked == false) {
$('.error-message-container').empty();
$('.error-message-container').append("<%= pdo.translate(" + checkBox.isObligatory + ") %>");
$('.error-message').show();
$('.bid-error').css("display", "block");
return false;
} else {
loading();
$.post("/inquiry.do?action=offer&ajax=1", formData,
function(data) {
window.top.location.href = data.redirectPage;
});
}
}
else
{
$('.error-message').show().text("PRICE IS NOT VALID");
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="offerInquiry">
Price 1
<input type="text" class="price" id="price1" value="0.00" />
<br/>Price 2
<input type="text" class="price" id="price1" value="0.00" />
<br/>
<input type='submit' />
<div class="error-message">ERROR!</div>
</form>

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Submit button using jQuery not working in IE9 and FF9

This submit button works in both Safari and Chrome but not IE9 or FF9.
Submit button -
<img type="submit" src="lib/send_feedback.jpg" border="0" class="feedback-submit-img" onClick="javascript: validate(); return false;"/>
Related jQuery -
// Submit form to next page
function submitForm() {
// document.forms["feedbackform"].submit();
document.feedbackform.submit();
}
// Submit form and validate email using RFC 2822 standard
function validateEmail(email) {
// Modified version original from: http://stackoverflow.com/a/46181/11236
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// Return true if email field is left unchanged
function originalText(email){
var defaultMsg;
defaultMsg = "Enter your email address (optional)";
if(defaultMsg == email){
return true;
}
return false;
}
// Verify or decline with error message
function validate(){
$("#result").text("");
var email = $("#email").val();
if ((validateEmail(email)) || originalText(email)) {
w.value = screen.width;
h.value = screen.height;
submitForm();
} else {
$("#result").text(email + " is not a valid email.");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
Also for what it's worth when I alter the submit button to be more basic to ensure it submits the hidden field that w and h are suppose to update are not filled in.
Here is the entire code and the CSS
type isn't a valid attribute of the img tag: https://developer.mozilla.org/En/HTML/Element/Img
Instead I think you want a <input type="image" /> tag: https://developer.mozilla.org/en/HTML/Element/Input.
The <img type="submit" /> didn't work for me either but using a <input type="image" /> did: http://jsfiddle.net/HXrNb/1/
You can then just bind the validate() function to the submit event for the form:
$('form').on('submit', function () {
...
if ((validateEmail(email)) || originalText(email)) {
...
return true;
} else {
...
return false;
}
});

Categories

Resources