Hi!
I've a HTML form
I've a function with some parameters that checks the value of each field (it's called within a onBlur event). This function check the type and other restrictions about that field.

I must create a function that checks that all required fields (or options or other kind of form field) are filled (or checked) before submit that form.

I thought to have a global variable where store the validation of each needed field, but I think there must be a better (smarter) way to do the job... and I'm a bit "worried" on fields that are not "editable" like options, checkboxes and so on...

Any suggestion will be appreciated!

TYIA

Dani AI

Generated

A cleaner, more maintainable pattern is to avoid a single global flag and instead attach small validator functions or metadata to each field as the form is generated. That fits well with ’s XML‑Schema generator: when you emit each input, include a data- attribute (or install a JS validator function) describing the type/pattern/required rule. Call the field’s validator on onblur, and on onsubmit iterate the form’s validators to collect errors. This keeps validation logic data-driven and easy to map from XSD types.

Keep it simple and robust — example workflow:

  • While generating the form, set data-required, data-validator="email|int|pattern:^\d+$", or attach a field._validator function.
  • For checkbox groups () validate by group name (e.g., document.querySelectorAll('input[name="reason"]:checked')) and, for each checked box, validate any linked explanation field via a data-explain-id attribute.
  • On submit, run every validator, build a short error list, focus the first bad field, and show inline messages or a single alert.

Small example (adapt to your generator):

function validateForm(form) {
  const errors = [];
  form.querySelectorAll('[data-required]').forEach(el => {
    const ok = el._validator ? el._validator(el) : (el.value || '').trim() !== '';
    if (!ok) errors.push(el.dataset.err || el.name || 'required field');
  });

  // checkbox group example
  const reasons = form.querySelectorAll('input[name="reason"]:checked');
  if (reasons.length === 0) errors.push('Select at least one reason');
  else reasons.forEach(cb => {
    const explain = document.getElementById(cb.dataset.explainId);
    if (explain && !explain.value.trim()) errors.push('Explanation required for ' + (cb.value || cb.name));
  });

  if (errors.length) { alert(errors.join('\n')); errors[0] && (form.querySelector('[name="'+errors[0]+'"]') || form).focus(); return false; }
  return true;
}

Notes and cautions: follow ’s lead and make validation generation-driven (server emits the right data- attributes). Do not rely solely on client checks — always revalidate on the server. For usability, prefer inline error text and set focus to the first invalid control.

Recommended Answers

All 8 Replies

On a large system I helped develop, we had this issue. Customers could order various products for print, and see a real-time PDF of the customized product before they ordered. Each product could have a custom form, and each form element could have custom validation. We didn't find any shortcuts! Sometimes coding is hard work.

Everything was database driven, and the site was written in classic ASP. We had a database table full of JavaScript validation routines we'd built-up over time. When the server script ran, it would make the appropriate event-handler assignments to the proper tags. We would dynamically author a single "validate" routine, and each object that required validation would call this function, passing itself in as a parameter. Based on the parameter/object, it would call the appropration clause in the routine to validate itself.

When you do the submit call the validation process and loop the form elements. Inside that loop create switch that contains all the form element types your form contains and then process each element based on it's type!

example...

<script>
<!-- //

	function good_add(eiv)
	{
		var teste = false;
		var strtest = new String(eiv);
		var index = strtest.indexOf("@");

		if (index > 0)
		{
			var eid = strtest.indexOf(".",index);

			if (eid > index+1 && strtest.length > eid+1)
			{
				teste = true;
			}

			return teste;
		}
	}

	function validate()
	{
		var e = '';

		for (var i = 0; i < document.test.elements.length; i++)
		{
    			var j = document.test.elements[i];

			switch (j.type)
			{
				case 'text':


				if (j.name == 'email')
				{
					if (j.value == '')
					{
						e += "Please enter a valid email\n";
					}
					else if (!good_add(j.value))
					{
						e += "Please enter a valid email\n";
					}
				}

				/* other 'input' type elements go here */

				break;

				case 'select-one':

				if (j.name == 'zip' && j.selectedIndex == 0)
				{
					e += "Please select a valid zip code\n";
				}

				/* other 'select' type elements go here */

				break;

				case 'checkbox':

				if (j.type == 'checkbox' && !j.checked)
				{
					e += "You must agree to our rules\n";
				}

				/* other 'checkbox' type elements go here */

				break;
			}
		}

		if ( e )
		{
			alert(e);

			return false;
		}
		else
		{
			/* submit would go here */

			// document.test.submit();
			// return true;

			alert('thanks for validating our form');

			return false;
		}
	}
// -->
</script>


<form name='test' action='process.php' onsubmit='return validate();' method='post'>
email <input type='text' name='email' value=''>
<br />
zip code <select name='zip'>
<option value=''>Select Zip Code
<option value='33510'>33510
<option value='02112'>02112</select>
<br />
<input type='checkbox' name='agree' value='1'> <small>do you agree with the rules</small>
<br />
<input type='submit' name='submit' value='Send'>
</form>

printf

ok thank you, I think that it's a good solution. I'll try it ;-)

(note: just to let you know my little job: I'm developing a solution that generates a form from a XML Schema file (that supports the fundamental types and structures) and I must have a "client-side" type check before the real submit... )

Thank you friends!
I hope to be able to help you in the future if you need help, obviously! ^_^

I'm wondering if I have a related issue.

I'm creating a form to request credit for customers for various reasons. There may be one reason, or more than one. As a result, I have a top section where the salesman enters in the account number, his ID number, the date, and the amount for the credit. The second section has checkboxes for each reason with a textbox for a detailed explaination. This way, they can select as many reasons as they need to. On the bottom, they enter in the name of the approving manager. Those are required. Optional is the ability to enter their own e-mail address to have the completed form mailed back to themselves, or to e-mail a link to the blank form to someone else.

I need to make sure that the top information (account, sales, date, amount) are filled in, that at least one checkbox is selected, that the textbox associated with that checkbox is filled in, and that there is something in the approval box when the form is submitted.

I want to verify this all client side before it gets submitted to the ASP file that e-mails it.

Would I use a similar method?

New links... those first ones won't work.



Thanks.

Had to change a few page references, but the links should all be working now for testing. But, I am definitely still in need of help.

Nevermind... was able to get help from a coworker...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.