You are viewing limited content. For full access, please sign in.

Question

Question

Forms JavaScript Validation - equalTo function

asked on November 25, 2015

Are there built-in functions I can use to validate the form beyond required? I ask this because I'm looking for an equalTo function of some kind to confirm a user's email address:

I wanted to use the jQuery validation tool and while it worked, it added its own error messages on top of the ones Forms generates for the required fields. I understand I can make my own JS function for this, but it would be a lot quicker and cleaner if it was already integrated somehow.

0 0

Answer

SELECTED ANSWER
replied on November 27, 2015 Show version history

I built a simple solution for generating an error. It should work for any kind of JS validation. Here's the custom JS I made for the equalTo function, calling functions I attached at the bottom:

$(document).ready(
  function () 
  {    
    var formValid = true; //variable to determine if the form inputs are valid; used for custom errors
    
    $('.emailAddress input, .confirmEmailAddress input').change
    (
      function ()
      {
        if($('.emailAddress input').val() != $('.confirmEmailAddress input').val())
        {
          formValid = false;
          showCustomError('.confirmEmailAddress', 'Please re-enter your correct email address.');
        }
        else
        {
          formValid = true;
          hideCustomError('.confirmEmailAddress');
        }
      }
    );
    
    $('input[type=submit]').click
    (
      function(e)
      {
        if(!formValid)
        {
          e.preventDefault(); //stop the form from being submitted
          showCustomError('.confirmEmailAddress', 'Please re-enter your correct email address.');
        }
        else
        {
          hideCustomError('.confirmEmailAddress');
        }
      }
    );   
});

The following functions show/hide the error messages:

//Using the provided element selector and message, add an error message next to the field
function showCustomError(elementSelector, errorMessage)
{
  hideCustomError(elementSelector); //remove previous error
  
  $(elementSelector + ' input').addClass('custom-error');
  $(elementSelector + ' input').focus();
  $(elementSelector + ' input').parent().append('<p class="custom-error-message">' + errorMessage + '</p>');
}

//Hide the custom error generated by the showCustomError function
function hideCustomError(elementSelector)
{
  $(elementSelector + ' input').removeClass('custom-error');
  $(elementSelector + ' input').siblings('.custom-error-message').remove();
}

 

Capture.PNG
Capture.PNG (11.27 KB)
2 0
replied on February 9, 2016

Michael,

I'm using this to help solve this problem I am having. Do you know how I would go about solving this? If the first check fails, I need it to do a second check - if that fails then I would like the error message. If one passes, then nothing needs to happen. My current code is:

$(document).ready(
  function () 
  {    
    var SCValid = true; //variable to determine if the form inputs are valid; used for custom errors
    
    $('input[id^=Field16], .SCCheck input').change
    (
      function ()
      {
        if($('input[id^=Field16]').val() != $('.SCCheck input').val())
        {
          SCValid = false;
          showCustomError('.LN', 'This Lot Number does not match the Sales Order - please verify.');
        }
        else
        {
          SCValid = true;
          hideCustomError('.LN');
        }
      }
    );
    
    $('input[type=submit]').click
    (
      function(e)
      {
        if(!SCValid)
        {
          e.preventDefault(); //stop the form from being submitted
          showCustomError('.LN', 'This Lot Number does not match the Sales Order - please verify.');
        }
        else
        {
          hideCustomError('.LN');
        }
      }
    );   
});

//Using the provided element selector and message, add an error message next to the field
function showCustomError(elementSelector, errorMessage)
{
  hideCustomError(elementSelector); //remove previous error
  
  $(elementSelector + ' input').addClass('custom-error');
  $(elementSelector + ' input').focus();
  $(elementSelector + ' input').parent().append('<p class="custom-error-message">' + errorMessage + '</p>');
}

//Hide the custom error generated by the showCustomError function
function hideCustomError(elementSelector)
{
  $(elementSelector + ' input').removeClass('custom-error');
  $(elementSelector + ' input').siblings('.custom-error-message').remove();
}

Currently I am having a couple issues. It only checks the first row in a table, when I need it to check every row. And it shows the error message before the user gets to the second field that is filled out. So as soon as there is an input in the first field, the error message pops up, even though the field is still blank. I would like the error message to pop-up only if the input is incorrect.

Any ideas how to accomplish this?

0 0
replied on February 9, 2016

Hi David,

My understanding is that you want to check if Field A is equal to Field B. If not, check that Field C and Field D are equal. If these are ALSO not equal, then show the error?

 

0 0
replied on February 9, 2016

Yes, that is correct. It's difficult because, in this scenario, Field A and C are from columns in a table. It seems that everything I try only checks the first row in the table.. 

0 0

Replies

replied on February 22, 2016 Show version history

Hi David,

I quickly put something together here but haven't been able to test it. I removed most of the code I had before to save space, so just be careful in that you're only copying the new code (which I've marked):

function checkFields()
{
    var formValid = true;
    validFieldA = [];
    validFieldC = [];
    validResult = []; //NEW LINE

    //check each fieldA input if they match with fieldB
    //-----------OLD CODE REMOVED-----------------//

    //check each fieldC input to see if they match with field D,
    //ONLY if the corresponding field A was invalid
    //-----------OLD CODE REMOVED-----------------//
    
    //NEW CODE
    //check that the result column is set to Pass. If not, the field and the form is invalid
    $('.fieldTable .result input').each(function (i, v)
    {
        if($(this).val() != 'Pass')
        {
            validResult[i] = false;
        }
        else
        {
            validResult[i] = true; 
        }

    });
    //END OF NEW CODE

    //for each of the LN inputs
    $.each($('.fieldTable .LN input'), function (i, v)
    {
        //check if the corresponding fieldA and fieldC inputs are invalid
        //but don't show errors caused by fieldA inputs being blank
        if(validFieldA[i] === false && validFieldC[i] === false && $(this).val() != '')
        {
            //-----------OLD CODE REMOVED-----------------//
        }
        //NEW CODE
        else if(validResult[i] === false)
        {
            //remove existing error
            $(this).removeClass('custom-error');
            $(this).siblings('.custom-error-message').remove();

            //show error
            $(this).addClass('custom-error');
            //$(this).focus(); //disabled focus
            $(this).parent().append('<p class="custom-error-message">ERROR MESSAGE HERE.</p>');

            //form is now invalid
            formValid = false; 
        }
        //END OF NEW CODE
        else
        {
            //this row is valid. Hide error for this row
            $(this).removeClass('custom-error');
            $(this).siblings('.custom-error-message').remove();
        }
    });
  
    //return true if there are NO errors
    return formValid;
}

Hope this helps.

1 0
replied on February 22, 2016 Show version history

This seems to be real close! I actually do not need any error message because the field returns back 'Pass', 'Fail' or 'Undetermined'. I commented out this portion of your code: 

      	//NEW CODE
        else if(validResult[i] === false)
        {
            //remove existing error
            //$(this).removeClass('custom-error');
            //$(this).siblings('.custom-error-message').remove();

            //show error
            //$(this).addClass('custom-error');
            //$(this).focus(); //disabled focus
            //$(this).parent().append('<p class="custom-error-message">Inspection did not pass</p>');

            //form is now invalid
            formValid = false; 
        }
        //END OF NEW CODE

But when I do that, it returns back the error message for if the two-part check does not match, even though it passes the two-part check, it just didn't pass inspection. If I comment out the entire section above, then the submit button is not disabled when the inspection fails.

 

Any thoughts?

0 0
replied on February 22, 2016

Only comment the "show error" section. You can leave the 2 lines below "remove existing error" lines un-commented.

1 0
replied on February 22, 2016

This seems to work!

 

Thanks!!

1 0
replied on March 1, 2016 Show version history

Michael

Sorry to keep bugging you! I have one more request. If field #q25 (css class "relabel") has an input of "RLBL" then I would like the check to only see if it passed or failed inspection (CSS class "result"). If #q25 reads anything but RLBL then it should stay the same. 
As a quick refresher - currently, the for checks fieldA against fieldB. If those don't match, it checks fieldC against fieldD. I those don't match it kicks back an error message and disables the submit button. Additionally, the submit button is disabled if the result is anything except pass. The part I'm needing to add isif #q25 == RLBL, ONLY check to see if result is Pass. I hope that makes sense. Let me know if I need to clarify anything, and thanks again so much for all the help!

 

Current code below:

$(document).ready(function(){
  $(document).on('change', '.ObjectivesColor input', function(){
    if ($(this).val() == 'Pass'){
      this.setAttribute('style', 'background-color: green !important');
    }
    else if ($(this).val() == 'Fail'){
      this.setAttribute('style', 'background-color: red !important');
    }
    else if ($(this).val() == 'Undetermined'){
      this.setAttribute('style', 'background-color: #fcc72e !important');
    }
    else {
      $(this).css('background-color', 'white');
    }
  });
});

$(document).ready(function(){
  $(document).on('change', '.ObjectivesColor input', function(){

    if ($(this).val() == 'Pass'){
      $(this).css('color', 'white');
    }
    else if ($(this).val() == 'Fail'){
      $(this).css('color', 'white');
    }
    else if ($(this).val() == 'Undetermined'){
      $(this).css('color', 'white');
    }
    else {$(this).css('color', 'black');}
  });
});









$(document).ready
(
  function () 
  {    
    //variable to determine if the form inputs are valid; used for custom errors
    var formValid = true; 

    //call the checkfields function if any input is changed
    // !!! modify this to only have it trigger when the user input is changed
    $('.fieldTable, .fieldB, .FieldD').on('change','input',
                                          function ()
                                          {
                                            formValid = checkFields();
                                          }
                                         );

    $('input[type=submit]').click
    (
      function(e)
      {
        //call the checkfields function again to see if all inputs are valid
        formValid = checkFields(); 
        if(!formValid)
        {
          e.preventDefault(); //stop the form from being submitted
        }
      }
    );  
  }
);
function checkFields()
{
  var formValid = true;
  validFieldA = [];
  validFieldC = [];
  validResult = [];

  //check each fieldA input if they match with fieldB
  $('.fieldTable .fieldA input').each(function (i, v)
                                      {
                                        if($(this).val() != $('.fieldB input').val())
                                        {
                                          validFieldA[i] = false;
                                        }
                                        else
                                        {
                                          validFieldA[i] = true;
                                        }
                                      });

  //check each fieldC input to see if they match with field D,
  //ONLY if the corresponding field A was invalid
  $('.fieldTable .fieldC input').each(function (i, v)
                                      {
                                        if(validFieldA[i] === false)
                                        {
                                          if($(this).val() != $('.fieldD input').val())
                                          {
                                            //both fieldA and fieldC are invalid
                                            validFieldC[i] = false;
                                          }
                                          else
                                          {
                                            //fieldA is invalid, fieldC is valid however
                                            validFieldC[i] = true;
                                          }
                                        }
                                        else
                                        {
                                          //fieldC may be valid or invalid, but fieldA is valid so it doesn't matter
                                          validFieldC[i] = true; 
                                        }

                                      });
  //NEW CODE
  //check that the result column is set to Pass. If not, the field and the form is invalid
  $('.fieldTable .result input').each(function (i, v)
                                      {
                                        if($(this).val() != 'Pass')
                                        {
                                          validResult[i] = false;
                                        }
                                        else
                                        {
                                          validResult[i] = true; 
                                        }

                                      });
  //END OF NEW CODE

  //for each of the fieldA inputs
  $.each($('.fieldTable .LN input'), function (i, v)
         {
           //check if the corresponding fieldA and fieldC inputs are invalid
           //but don't show errors caused by fieldA inputs being blank
           if(validFieldA[i] == false && validFieldC[i] == false && $(this).val() != '')
           {
             //remove existing error
             $(this).removeClass('custom-error');
             $(this).siblings('.custom-error-message').remove();

             //show error
             $(this).addClass('custom-error');
             //$(this).focus(); //disabled focus
             $(this).parent().append('<p class="custom-error-message">This Lot Number does not match the Sales Order - please verify.</p>');

             //form is now invalid
             formValid = false; 
           }
           //NEW CODE
           else if(validResult[i] === false)
           {
             //remove existing error
             $(this).removeClass('custom-error');
             $(this).siblings('.custom-error-message').remove();

             //show error
             //$(this).addClass('custom-error');
             //$(this).focus(); //disabled focus
             //$(this).parent().append('<p class="custom-error-message">Inspection did not pass</p>');

             //form is now invalid
             formValid = false; 
           }
           //END OF NEW CODE
           else
           {
             //this row is valid. Hide error for this row
             $(this).removeClass('custom-error');
             $(this).siblings('.custom-error-message').remove();
           }
         });

  //return true if there are NO errors
  return formValid;
}

Thanks!!

replied on February 9, 2016 Show version history

Hi David,

Something like this?

I had to modify the code a fair bit so you will have to make some changes to the variables and the input fields that trigger the event, but hopefully this helps. For the sake of simplicity, I changed the field names to fieldA (Lot Check), fieldB (Stock Check Code), fieldC (AltKey2), and fieldD (2AltKey2). You will want to change those to your corresponding CSS classes/IDs.

$(document).ready
(
	function () 
	{    
		//variable to determine if the form inputs are valid; used for custom errors
		var formValid = true; 
		
		//call the checkfields function if any input is changed
		// !!! modify this to only have it trigger when the user input is changed
		$('.fieldTable, .fieldB, .FieldD').on('change','input',
			function ()
			{
				formValid = checkFields();
			}
		);
	  
		$('input[type=submit]').click
		(
			function(e)
			{
				//call the checkfields function again to see if all inputs are valid
				formValid = checkFields(); 
				if(!formValid)
				{
					e.preventDefault(); //stop the form from being submitted
				}
			}
		);  
	}
);
function checkFields()
{
	var formValid = true;
	validFieldA = [];
	validFieldC = [];

	//check each fieldA input if they match with fieldB
	$('.fieldTable .fieldA input').each(function (i, v)
	{
		if($(this).val() != $('.fieldB input').val())
		{
			validFieldA[i] = false;
		}
		else
		{
			validFieldA[i] = true;
		}
	});

	//check each fieldC input to see if they match with field D,
	//ONLY if the corresponding field A was invalid
	$('.fieldTable .fieldC input').each(function (i, v)
	{
		if(validFieldA[i] === false)
		{
			if($(this).val() != $('.fieldD input').val())
			{
				//both fieldA and fieldC are invalid
				validFieldC[i] = false;
			}
			else
			{
				//fieldA is invalid, fieldC is valid however
				validFieldC[i] = true;
			}
		}
		else
		{
			//fieldC may be valid or invalid, but fieldA is valid so it doesn't matter
			validFieldC[i] = true; 
		}

	});

	//for each of the fieldA inputs
	$.each($('.fieldTable .fieldA input'), function (i, v)
	{
		//check if the corresponding fieldA and fieldC inputs are invalid
		//but don't show errors caused by fieldA inputs being blank
		if(validFieldA[i] == false && validFieldC[i] == false && $(this).val() != '')
		{
			//remove existing error
			$(this).removeClass('custom-error');
			$(this).siblings('.custom-error-message').remove();

			//show error
			$(this).addClass('custom-error');
			//$(this).focus(); //disabled focus
			$(this).parent().append('<p class="custom-error-message">This Lot Number does not match the Sales Order - please verify.</p>');

			//form is now invalid
			formValid = false; 
		}
		else
		{
			//this row is valid. Hide error for this row
			$(this).removeClass('custom-error');
			$(this).siblings('.custom-error-message').remove();
		}
	});
  
	//return true if there are NO errors
	return formValid;
}

 

0 0
replied on February 9, 2016

This is amazing!! Thank you so much!! The ONLY request I have - how to I make the error message appear under the column with CSS class .LN instead of under .fieldA?

0 0
replied on February 9, 2016 Show version history

No problem! Change Line 76 in the above code from:

$.each($('.fieldTable .fieldA input'), function (i, v)

to:

$.each($('.fieldTable .LN input'), function (i, v)

Note that with this change, errors won't be shown unless the corresponding .LA input is NOT blank. I am assuming that's the intent.

0 0
replied on February 9, 2016

Perfect! Seriously thank you so much. I've been struggling with this for awhile now.

Thank you!

0 0
replied on February 9, 2016

Glad to help!

0 0
replied on February 9, 2016

If you would like to post this answer on my original question, I can denote it as the correct answer and everything. That way you get the points for solving it. I'm not sure what the points do or are for, but I'd be happy to give them to ya.

1 0
replied on February 9, 2016

Done. Thanks David!

0 0
replied on February 22, 2016

Michael,

I was wondering if you would be able to help with one more thing related to this form (Sorry!). Currently, the submit button is disabled when the match fails, which is perfect. But I also need it to be disabled if the Pass/Fail column reads either "Fail" or "Undetermined". Basically I only want the submit button enabled if all columns have "Pass" in the Pass/Fail Column. I've given this column the css class "result".

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.