Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Form validation

Featured Replies

Hi,

 

I've just produced a form using pure css and not a table in sight. Very proud and happy with the result.

 

The form submits via php. Works beautifully!

 

But now the client wants me to validate various fields - ie the form can't be sent unless the user enters their name.

 

Just because I like to make things difficult for myself, I think it would be great if the field that needs to be completed changes background colour.

 

I've scoured the web and I thought I'd found some great javascript code to answer my prayers but it aint working.

 

I notice in the sample I've used the form was built using tables. Mine was built without them and is styled from the stylesheet.

 

So does that mean the javascript doesn't have any effect on the form colours?

 

Here's the javascript:

 	<script type="text/javascript">

function validateFormOnSubmit(theForm) {
var reason = "";

 reason += validateEmpty(theForm.name);
 reason += validateEmpty(theForm.email);
 reason += validateEmpty(theForm.companyname);
 reason += validateEmpty(theForm.address);
 reason += validateEmpty(theForm.city);
 reason += validateEmpty(theForm.postcode);
 reason += validateEmpty(theForm.enquiry);

 if (reason != "") {
   alert("Some fields need correction:\n" + reason);
   return false;
 }

 return true;
}

function validateEmpty(fld) {
   var error = "";

   if (fld.value.length == 0) {
       fld.style.background = 'Yellow'; 
       error = "The required field has not been filled in.\n"
   } else {
       fld.style.background = 'White';
   }
   return error;   
}
</script>

 

 

Thanks for any advice.

 

Jo

Hi Jo,

How are you calling this script? via onsubmit?

Do your form fields have 'name' values corresponding to the script?

If you could show the html, that would help.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.