Validating individual form inputs with javascript - javascript

I have a registration form that validates a text field, if it's empty when a user clicks/tabs off which shows an error message. My issue with the below code is its a lot to duplicate across several form fields. The below example is for first name but I can't see a way of using what I have to do the same for more than one field.
/* this will call ajax call after entering all the below three fiels */
var $fields = $('#testid');
$fields.live('blur',function(e) {
e.preventDefault();
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if ($emptyFields.length) {
var frm = $(this).parents('form');
var url=$('#valNameEmail').val();
jQuery.ajax({
url: url,
data: $(this).parents('form').serialize(),
type: 'POST',
dataType: "json",
success: function(response){
if (response.HtmlMessage === 'success'){
$('.reg-alreadyRegistered').html('');
$('.reg-alreadyRegistered').css('display', 'none');
ACC.registration.tickIcon($('#testid'));
var radioExCustValue = $('#registration-form input[name=existingCustomer]:checked').val();
if (userNameAjax === true) {
if (radioExCustValue == 'false'){
$('#regFormSubmit').removeAttr('disabled');
}
else {
if (customerValidation == true){
$('#regFormSubmit').removeAttr('disabled');
}
}
}
emailIDajax = true;
} else {
ACC.registration.errorIcon($('#testid'));
$('.reg-alreadyRegistered').html(response.HtmlMessage);
$('.reg-alreadyRegistered').css('display', 'block');
emailIDajax = false;
$('#regFormSubmit').attr('disabled','disabled');
}
},
error: function(){
//alert(response);
//console.log('ERROR!')
}
});
}
});

You can give the same inputs that require same sort of validation a class (or if you want it for example for all input[type=text] then you can use it for the selector.
So let's say I have a form like this:
<form id="mform">
<input type="text" class="inptxt" name="it1" />
<input type="text" class="inptxt" name="it2" />
<!-- other similar text inputs with the same class -->
<input type="submit" id="sub" value="Submit" />
</form>
I have a function for text inputs which returns false if the field is empty, otherwise true:
$.fn.isValid = function() {
return $.trim($(this).val());
}
And then I get the inputs by class and validate them all at once:
$('#mform').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$('.inptxt').each(function() {
if (!$(this).isValid()) {
$(this).css('background-color', 'red');
allValid = false;
}
else
$(this).css('background-color', 'white');
});
if(allValid) {
//everything's valid ... submit the form
}
});
jsfiddle DEMO

This worked for me:
$('#registration-form input').blur(function(){
if( $(this).val().length === 0 ) {
ACC.registration.errorIcon($(this));
}
else{
ACC.registration.tickIcon($(this));
}
});
thanks for your help

Related

Google captcha v3 button twice click is need to complete action

I just installed recaptcha v3 on a form and I found that the submit button needs to be clicked 2x to make it work.First submit it will get the captcha validation. After the second click it will pass redirect.
Html code
<div class="form_wrpr">
<f:form.hidden id="g-recaptcha-response" property="g-recaptcha-response" />
<button class="g-recaptcha btn btn-blue" id="reg-submit"
data-sitekey="{fields.clientKey}" data-callback='onSubmit' data-action='submit' type= "submit">
{fields.Button}</button>
</div>
Script
$("#reg-submit").on('click', function(){if($('#company').val() == '') {
$('#company_error').text($('#company_error').data("error-mandatory"));
isvalid4 = false;
} if(!isvalid4) {
return false; }
if (grecaptcha.getResponse().length != 0) {
$("#reg-submit").attr("disabled", true);
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
$('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if(output.error == 1) {
$('#form-errors').html(output.result);
}
else if(output.error == 2){
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
} } }); }else { var elementClicked = 0;
$(".g-recaptcha").on('click', function(){
elementClicked = 1; if( elementClicked == 1)
{ $('#g_captchaerror').text(''); } }); if(elementClicked == 0)
{ isvalid4 = false;
$('#g_captchaerror').text($('#g_captchaerror').data("error-mandatory"));
} } });
The code creates a button that a user must click on in order to complete the CAPTCHA challenge. When the button is clicked, the grecaptcha.execute() function is called, which will trigger the reCAPTCHA v3 verification process.
$(document).ready(function() {
var alreadySubmitted = false;//adding a extra variable to check already submitted.
$("#reg-submit").on('click', function(){
if(!isvalid4) {
return false;
}
grecaptcha.ready(function() {
grecaptcha.execute('clientkey', {
action: 'submit'
}).then(function(token) {
$.ajax({
type: 'POST',
url: $('#form-ajaxurl').val(),
data: $('#demo_form').serialize(),
success: function(data){
// $('#reg-submit').attr("disabled", false);
var output = JSON.parse(data);
if (output.error == 1) {
$('#form-errors').html(output.result);
} else if(output.error == 2) {
$('#form-errors').html(output.result);
} else {
window.location.href = 'test.com'+output.result;
}
}
});
});
});
});

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

Exiting from javascript function not working

I have this javascript function:
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
}
What am hoping this achieves is, if the input field is empty, display the alert and remain in the function.If it isn't then continue.
My submit button is linked to another page but this page is displayed anyways regardless of what happens in the if statement.
This is the form code:
<form id="post" action="http://localhost:8080/uploadNewMessage" method="post">
<fieldset>
<div data-role="fieldcontain">
<label for="msg" class="input">Message:</label>
<input type="text" name="msg" id="msg" size="10"/>
</div>
Submit
</fieldset>
</form>
and the full javascript code just incase:
$(document).ready(function() {
// 1. The Registration button
$("#submit").bind('click', function(event) {
displayMessage();
});
});
function doPostRequest(postData) {
$.ajax({
type: "POST",
url: URL,
dataType: "json",
data: postData
});
}
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
doPostRequest(postData);
}
You may try something like this:
$("#submit").bind('click', function(event) {
var message = $.trim($("#msg").val());
if(!message.length) {
alert("You need to enter a message");
return false;
}
else {
event.preventDefault();
doPostRequest({"message":message});
}
});
demo
$(function() {
$("#submit").on('click', function(event) {
event.preventDefault(); // prevent default anchor behavior
displayMessage();
});
});
and also:
function displayMessage() {
var message = $.trim( $("#msg").val() ); // trim whitespaces
if (message === "") {
alert("You need to enter a message");
}else{ // Use the else statement
doPostRequest({
"message" : message
});
}
}
The event variable that is passed via your click event handler contains a function named preventDefault. If you don't want the form to submit, call this (event.preventDefault()). This will prevent the submit button from submitting the form.

Is there a way to prevent submitting a form with this javascript/jquery?

I have searched the net, i´ve tried implementing "preventdefaults" and "return false" statements all over the place, but I can´t seem to find a way to prevent this form submitting and reloading the page. It only reloads when the form has been validated. I´m kind of a beginner, but I really tried hard achieving the script to validate a form (which has "post"-method and "#" as action), and make an ajax-call. It´s a school assignment and would be graceful towards any pointers you guys could give.
$(document).ready(function()
{
$("#submit").click(function()
{
var gbname = $("#gbname")[0];
var gbmessage = $("#gbmessage")[0];
formFields = [gbname, gbmessage]
var warning = false;
for (i=0; i<formFields.length; i++)
{
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "")
{
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true)
{
alert("Vänligen fyll i fälten korrekt!");
return false;
}
else
{
$.post('ajax.php', {gbname: gbname, gbmessage: gbmessage},
function(data)
{
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" +gbname+ "</p> <p class='messages'><b>Meddelande:</b>" +gbmessage+ "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
});
return false;
}
return false;
});
});
Your references to the input elements as objects and the data returned from your AJAX call were a bit muddled.
Also incorporated the suggestion of binding to the form's submit event. DEMO
$(document).ready(function () {
function clearForm(){
$('input.reset').each(function(){
$(this).val('');
});
}
$("form").on('submit', function () {
alert('submitted!');
var gbname = $("#gbname");
var gbmessage = $("#gbmessage");
formFields = [gbname[0], gbmessage[0]]
var warning = false;
for (i = 0; i < formFields.length; i++) {
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "") {
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true) {
alert("Vänligen fyll i fälten korrekt!");
return false;
} else {
var J = JSON.stringify({
"gbname": gbname.val(),
"gbmessage": gbmessage.val()
});
console.log(J);
$.ajax({
type: "POST",
url: '/echo/json/',
datatype: 'json',
data: {
json: J,
delay: 3
},
success: function (data) {
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" + data.gbname + "</p> <p class='messages'><b>Meddelande:</b>" + data.gbmessage + "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
} // end success
}); // end ajax
return false;
} // end else
return false;
});
});
I suggest using
$("form").on('submit', function (e) {
[...]
if(validationErrors) {
alert(Errormessage);
e.preventDefault();
}
[...]
instead of returning false.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
In order to get it to work, you have to use the event as a parameter of your callback function.

Prevent AJAX form from submitting twice?

I can't figure out why this AJAX form is processing and sending out an email twice. Is there some sort of obvious hickup in the code you can see causing this to occur?
HTML
<form class="submit-form" method="post">
<input type="url" class="content-link" name="content_link" placeholder="Link" />
<input type="email" class="email" name="email" placeholder="Your Email Address" />
<button class="submit-modal-button submit-button"><span>Send<span class="ss-icon">send</span></span></button>
<p class="terms">By clicking Submit you agree to our Terms & Conditions</p>
</form>
JavaScript
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]'),
viewport_size = $(window).width() + "x" + $(window).height(),
user_browser = BrowserDetect.browser,
user_os = BrowserDetect.OS,
current_page = document.location.href;
$('.submit-form input[type="url"],.submit-form input[type="email"]').blur(function () {
if ($.trim($(this).val()) == '') {
$(this).addClass('form-validation-error');
return false;
} else {
$(this).removeClass('form-validation-error');
}
});
form.submit(function () {
if ($.trim(content_link.val()) == '' && $.trim(email.val()) == '') {
content_link.addClass('form-validation-error');
email.addClass('form-validation-error');
return false;
}
else if ($.trim(content_link.val()) == '') {
content_link.addClass('form-validation-error');
return false;
}
else if ($.trim(email.val()) == '') {
email.addClass('form-validation-error');
return false;
} else {
var env = TTB.getEnvironment();
$('.submit-modal-button').attr('disabled','disabled');
$(document).ajaxStart(function () {
$('.submit-modal .screen-1').delay(300).append('<span class="loading2"></span>');
});
$.ajax({
url: env.submit_modal_process,
type: 'POST',
data: {
    content_link: content_link.val(),
    email: email.val(),
viewportsize: viewport_size,
browser: user_browser,
os: user_os,
current_page: current_page
  },
success: function () {
$('.submit-modal .screen-1').delay(1000).fadeOut(300, function () {
$('.submit-modal .screen-1').fadeOut(500, function () {
$('span.loading2').detach();
$('.submit-modal .screen-2').fadeIn(500, function () {
$('.submit-modal .screen-2').append('<img class="carlton" src=' + env.the_environment + TTB.config.image_path() + 'submit-modal-success.gif' + ' />');
});
$('.submit-modal .screen-2').css('display','block').delay(4200).fadeOut(500, function () {
$('.carlton').hide();
$('.submit-modal .screen-1').fadeIn(500);
content_link.val('');
email.val('');
content_link.focus();
email.removeClass('form-validation-error');
$('.submit-modal-button').removeAttr('disabled');
});
});
});
}
});
return false;
}
});
}
EXAMPLE.processSubmitModal();
If to remove all non relevant to the issue code from your snippets we will get the following:
HTML
<form class="submit-form" method="post">
<input type="url" name="content_link" />
<input type="email" name="email" />
<button>Send</button>
</form>
JavaScript
$(function() {
var EXAMPLE = {
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]');
form.submit(function () {
$.ajax({
url: document.location.href,
type: 'POST',
data: {
content_link: content_link.val(),
email: email.val()
},
success: function () { // <-- The function that is executed twice
// Do something
}
});
return false;
});
}
};
EXAMPLE.processSubmitModal();
// And somewhere in the code that was not presented in snippet...
EXAMPLE.processSubmitModal();
});
I played around with your snippet and it always performs only one AJAX call and process email once except the only case - when somewhere in the code you call EXAMPLE.processSubmitModal() once again. Search in your code, I'm almost sure it is the reason. Pay attention that each time you call EXAMPLE.processSubmitModal() you add one another handler to submit event of the form and not override it.
Try like this
form.submit(function (event) {
if(event.handled !== true)
{
//put your ajax code
event.handled = true;
}
return false;
});
Refernce

Categories

Resources