jquery required field validator issue - javascript

I have a form with multiple input fields and a select field. I have an attribute of required for multiple fields. I have created a validation code snippet which should check all required fields and display a message when field is empty.
However the problem is that it works only when first input field is empty. I would appriciate a hint.
Code for the function:
function lisa_a() {
//validator
var req = $(":input[required]").val();
var reqfield = $(":input[required]");
if (req == ""){
$(".error").remove();
var reqtxt = "<span class='error'>Nõutud</span>";
reqfield.each(function(){
$(this).after(reqtxt);
});
$("div#status").html("Please fill...");
//validator
}else{
var data = $("form#lisa_a_vorm").serialize();
$.ajax({
url : "/var_dump.php", //for testing
method: "POST",
data : data,
success:function(data) {
$("div#status").html(data);
}
});
$("form#lisa_a_vorm :input").each(function(){
$(this).val('');
});
$(".error").remove();
}
}
EDIT:
Searched some more and discovered .filter looping through fields. Adjusted my code:
function lisa_a() {
//validator
var emptyfields = $(":input[required]").filter(function(){
return $.trim($(this).val()).length === 0;
}).length > 0;
$(".error").remove();
if (emptyfields){
$(":input[required]").after("<span class='error'>Nõutud</span>");
$("div#status").html("Palun täida kõik nõutud väljad!");
}else{
var data = $("form#lisa_a_vorm").serialize();
$.ajax({
url : "/wp-content/themes/origin/TCDB/php/var_dump.php",
method: "POST",
data : data,
success:function(data) {
$("div#status").html(data);
}
});
$("form#lisa_a_vorm :input").each(function(){
$(this).val('');
});
$(".error").remove();
}
}
It's not perfect as i don't quite understand .filter basics. Am i correct if i say that the filter function returns the number of trimmed required input fields that have the value 0, which means that they are empty. If the number of those fields is greater than 0, then it returns true, else it returns false. EDIT: i think i just got the point. The solution came from this answer.

Related

editing input fields together instead of separately

Current Scenario :
Right now I have a form in which you can edit and save each records of input fields. i.e. firstName, lastName, email etc..
I do not get any errors and everything is working fine.
Requirement :
Now what I want to save & edit firstName and lastName input fields together instead is to edit and save firstName and lastName input field separately.
Right now they are all different input id's.
Question :
How can I achieve this by calling the same class for firstName and lastName if I want to edit them at the same time with a button ?
Is this a way to do it ? Thanks...
Code :
$("#inputFirstName,#inputLastName,#inputEmailAddress,#inputPassword,#inputZipCode").on('keypress',function(e){
if(e.which == 13) {
var field = $(this).attr("id");
var data = {};
data['ajax']=true;
data[$('#'+field).attr('name')]=$('#'+field).val();
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][firstName]') {
$('#userfirstname').text($('#'+field).val());
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][lastName]') {
$('#userlastname').text($('#'+field).val());
}
});
$('#'+field+'-edit').show();
$('#'+field+'-save').hide()
$('#'+field).attr('disabled',true);
}
});
first of all. save on every keypress is bad and will exhaust your server.
I recommennd you use onChange or make a submit button
submit button is a better solution.
lets assume that we have this html:
<form id="updateForm">
<input type="text" id="firstN" name="firstName" data-val="Ris" value="Ris">
.
.
.
<input type="button" value="submit" id="goBtn">
</form>
first set a data-val equal to the value
then in your javascript
$("#goBtn").click(function(){
var data = {};
data["ajax"] = true;
$("#updateForm input").each(function(){
var $this = $(this);
var type = $this.attr('type');
if(type != "button" && $this.val() != $this.attr("data-val"))
data[$this.attr("name")] = $this.val();
});
if(data.length > 0){
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
} else {
$.each(data, function(index, value){
$('updateForm input[name="'+index+'"]').attr("data-val", value);
});
}
// then do things
});
}
});
first it checks every input for changes (data-val is holding the original value) and it adds it to data if there is any changes at all it calls the ajax and if it was successful it updates the data-vals of each changed value else it leave it for another submission

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

jQuery $.post not executing, how to fix

I am working on a Plugin for WordPress and am having issues with the js code below executing the $.post.
The js is called, form validation takes place, the form inputs are serialized into post data correctly, the $.post just doesn't execute.
The form is being posted from the Admin, currently I can't get the .submit action to work so am using .click to execute the js function. This may be related to the issue, I am not sure... The form will load without submitting if I use the .submit action, versus using the .click action... never had this issue before and it is pretty frustrating to say the least.
Here is the code:
jQuery(document).ready(function($) {
$("#edit_member_submit").click( function() {
// define
var numbers = /^[0-9]+$/;
var referrer_id = $("#referrer_id").val();
// Validate fields START
if( !referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
// Define a data object to send to our PHP
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
var data = $("#edit_member_form").serializeObject(); //the dynamic form elements.
//alert(JSON.stringify(data));
data.action = "edit_member_info"; //the action to call
data._ajax_nonce = custajaxobj.nonce; // This is the name of the nonce setup in the localize_script
// Define the URL for the AJAX to call
var url = custajaxobj.ajaxurl;
//alert( JSON.stringify( data ) );
//alert( JSON.stringify( url ) );
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
return false;
});
});
Seems like the last section is having issues:
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
$.post( "ajax/test.html", function( data ) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(data);
});

Change javascript validation on form to onblur or onchange instead of submit

I have a form that validates php and javascript.
I would like to change the javascript validation to real time. I have it setup so classes and messages are added if user enters proper information or incorrect information after clicking the submit button. This is a validation I have used for awhile and would like to update to be a live validation. I have tried to add onblur(myFunction) etc to the input fields with a corresponding function. That does not seem to work. I am a javascript noob. I realize the script will need quite a bit of overhaul, however can someone point me in the right direction. I realize there is a jquery plugin that does some of this, however I would like to learn how its happening rather than using an existing code.
$(function () {
$('#contact_form').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
*validation here*
if (pcount == 0 && pcount2 == 0 && pcount3 == 0) {
submit_form = true;
}
if (submit_form) {
$('#loader', form).html('<img src="assets/img/loader.gif" /> Please Wait...');
$.ajax({
type : 'POST',
url : post_url,
data : post_data,
success : function(msg) {
$(form).fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
}
});
});
It is not so hard to do, just separate the sending and the validation like this:
$.fn.validateMyForm = function() {
var form = $(this);
/* validation */
if (pcount == 0 && pcount2 == 0 && pcount3 == 0) {
return true;
}
return false;
}
$(function () {
$('#contact_form').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
if ($(form).validateMyForm()) {
/* ajax sending */
});
}
});
And then add the validation on the blur events where needed:
$("input").blur({
$('#contact_form').validateMyForm();
});

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources