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.

Contact Form - Pop-up error on fields

Featured Replies

Through the guidance of a tutorial I have been able to add a 'hint' pop-up to a field within a contact form I put together using CSS.

 

However, I'd like to know how to add an 'error' pop-up for each field similar to how the BBC has when you attempt to register an online account with them [https://ssl.bbc.co.uk/id/register].

 

The CSS I used to create the 'hint':

.form_hint::before {
    content: "\25C0"; /* left point triangle in escaped unicode */
    color:#575974;
    position: absolute;
    top:1px;
    left:-6px;
}

.contact_form input:focus + .form_hint {display: inline;}
.contact_form input:required:valid + .form_hint {background: #28921f;} /* change form hint color when valid */
.contact_form input:required:valid + .form_hint::before {color:#28921f;} /* change form hint arrow color when valid */

The HTML for the form:

  <form name="myform" class="cssform contact_form" action="contactus.php" method="post">
    <div class="field" style="margin-top: 8px;">
      <label id="Name">Name*</label>
      <input name="Name" type="text" id="name" value="" />
    </div> <!-- field -->
    <div class="field">
      <label id="Email">Email*</label>
      <input name="Email" type="text" id="email" value="" />
    <span class="form_hint"><strong>Example</strong><br />name@something.com</span>
    </div> <!-- field -->
    <div class="field">
      <label id="Telephone">Telephone<span style="color: #FFF;">*</span></label>
      <input name="Telephone" type="text" id="telephone" value="" />
    </div> <!-- field -->
	<div class="field">
      <label id="Comments">Comment(s)*</label>
      <textarea name="Comments" style="width: 304px;" cols="0" rows="5" id="enquiries"></textarea>
    </div> <!-- field -->
    
    <div class="submitwrapper">
	<div class="inforequired"><em>*Information is required</em></div>
	<div class="submitbutton"><img onclick="verify()" src="images/contact-us/submit.png" alt="Submit" /></div> 
	</div> <!-- submitwrapper -->
  </form>

The page with the form:

http://nialldevlin.com/contactus.html

 

Hope I've included all the necessaries!

You're gonna need some JavaScript to detect errors. the simplest things to check are if a required field is blank, after that comes setting minimum / maximum character lengths. Then more complex is using regular expressions to validate things like email-addresses, post codes etc.

 

Either way, this is not possible with css alone.

 

Here is a validator I wrote (uses jQuery)

/*------------------------------------*\
    #REALTIME VALIDATE
\*------------------------------------*/

/* Real time validation for forms 
	NOTE THIS IS JUST FOR VISUAL FEEDBACK FOR THE USER, THIS SHOULD NOT BE USED IN PLACE OF SERVER SIDE VALIDATION.

	To use on a form it should be given a class of '.js-realtime-validate'
		it's input elements, textareas selects should be given a class that relates to the type of data expected:

		E.g:
		<form class="js-realtime-validate">
			<ul class="bare-list">
				<li>
					<label for="name">*Namn</label>
					<input type="text" class="text-input" data-min-length="10" name="name" id="name" required>
				</li>
				<li>
					<label for="email">*E-post</label>
					<input type="email" class="text-input" data-min-length="5" name="email" id="email" required>
				</li>
				<li>
					<label for="telephone">Telefon</label>
					<input type="tel" class="text-input" name="telephone" id="telephone" data-min-length="9" required>
				</li>
				<li>
					<label for="message">*Vad har du på hjärtat?</label>
					<textarea name="message" class="textarea-input" id="message" required></textarea>
				</li>
				<li>
					<select name="country" required>
						<option value="" selected disabled>Select country</option>
						<option value="England">England</option>
					</select>
				</li>
				<li><button type="submit">Skicka</button></li>
			</ul>
		</form>

		--- the data-min-length attribute gives the field a minimum length that the function also uses to determine if the 
			field is valid.  This function does not prevent the form from submitting, it's merely visual feedback to the user.
*/


(function() {
	function realTimeValidate() {
		
		var form = $(this); // The current form to validate.

		function processInput() {
				var input = $(this),
				validInputLength,
				inputValid = false;

			function checkIfValidLength() {
				var requiredLength = input.data('min-length') || 1,
					actualLength;
					if (input.val()) {
						actualLength = input.val().length;
					} else {
						actualLength = 0;
					}
				if(actualLength - requiredLength >= 0) {
					return true;
				}
				return false;
			}

			function checkIfValidValue() {

				// checks if the input is a vaild value. returns true or false
				var value = input.val();

				function testEmail(val) {
					// test value against regular expression.
					var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
					return re.test(val);
				}

				function testNumber(val) {
					// test value against regular expression.
					var re = /^[0-9]+$/;
					return re.test(val);
				}

				function testTelephone(val) {
					// test value against regular expression.
					var re = /^\+?\d+(-\d+)*$/;
					if (val.length >= 9) {
						return re.test(val);
					}
					return false;
				}

				if (input.attr('type') === 'text' || input.is('textarea')) {
					// no regular expression required to test text input or textarea / select
					return true;
				} else if (input.attr('type') === 'email') {
					// return result of testEmail
					return testEmail(value);
				} else if (input.attr('type') === 'number') {
					// return result of testNumber
					return testNumber(value);
				}
				else if (input.attr('type') === 'tel') {
					// return result of testTelephone
					return testTelephone(value);
				} else if (input.is('select')) {
					// return value 
					return (input.val());
				} else {
					return true;
				}
			}

			if (input.attr('required')) {
				validInputLength = checkIfValidLength();
				// assign result of checkIfValidLengthto validInputLength
				if (validInputLength) {
					// if valid length then assign result of checkIfValidValue to inputValid
					inputValid = checkIfValidValue();
				}
			} else {
				// input is not required.
				inputValid = true;
			}

			if (inputValid) {
				input.addClass('valid').removeClass('invalid');
				return true;
			} else {
				input.addClass('invalid').removeClass('valid');
				return false;
			}
		}

		function userActionSubmit() {
			// Go through each form element to check to validity.
			var valid = true;
			form.find('input, textarea, select').each(function() {
				var validReturn = processInput.call($(this));
				if (!validReturn) {
					valid = false;
				}
			});
			return valid;
		}

		// check for user interraction
		form.find('button[type="submit"]').on('click', userActionSubmit);
		
		form.submit(function(event){
		    if(!userActionSubmit()) {
		   		event.preventDefault();
		    }
		});
		form.find('input, textarea').on('blur', processInput);
		form.find('select').on('change', processInput);
		form.find('input, textarea').on('input', function() {
			if ($(this).hasClass('valid') || $(this).hasClass('invalid')) {
				processInput.call($(this));
			}
		});
	}

	// call realTimeValidate function on any present forms with classname.
	$('.js-realtime-validate').each(realTimeValidate);
}());

I haven't had the time to FULLY test this yet so if you want to use it I'd recommend you use it for testing / learning purposes and not in production.

  • Author

Thanks very much rbrtsmith, I combined that with my existing CSS and it seems to be working well.

 

How can I customise the messages so that they fit more in line with the overall theme?

Mine doesn't output messages, it just adds a class to an invalid form element. You'd need to extend my JavaScript to add in error messaging. I think in most cases, if the form element is correctly labeled and contains an appropiate placeholder then a change in border-color or similar to illustrate valid and invalid entries is suffice.

  • Author

Thanks rbrtsmith, appreciate the help.

 

I found a jQuery plug-in called bValidator that allows me to add and customise error messages - I get the following when I run the page through W3C Validator though.

 

 

 

  1. error.png Line 131, Column 89: there is no attribute "data-bvalidator"
    …border: solid thin #575974;" type="text" data-bvalidator="required,alphanum" />

    ✉

    You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Transitional" document type to get the "target" attribute), or by using vendor proprietary extensions such as "marginheight" (this is usually fixed by using CSS to achieve the desired effect instead).

    This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information.

    How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the <embed> element to incorporate flash media in a Web page, see the FAQ item on valid flash.

 

Is there a way to stop these message while keeping bValidator?

 

Other than this it seems to be working fine.

Set your doctype for html5

<!DOCTYPE html>

There is almost no reason all of your pages should have this going forward. The attr data-bvalidator is valid under html5. That being said, if it still doesn't validate because of that, then the validator is wrong and you should just ignore that.

  • Author

Thanks cibgraphics, that works now - sorry I didn't reply sooner.

 

Should I be concerned by the following W3C Validator warning?

 

info.pngUsing experimental feature: HTML5 Conformance Checker.

The validator checked your document with an experimental feature: HTML5 Conformance Checker. This feature has been made available for your convenience, but be aware that it may be unreliable, or not perfectly up to date with the latest development of some cutting-edge technologies. If you find any issues with this feature, please report them. Thank you.

Edited by Demonolith

Thanks cibgraphics, that works now - sorry I didn't reply sooner.

 

Should I be concerned by the following W3C Validator warning?

 

 

W3C is a 'guide', there's many things it has yet to comprehend, 'Warning' and 'Invalid' are two different things.

 

Edit: Forgot to say, as rbrtsmith says that java validation is great for visual prompt just not as a safeguard; whatever you need to validate from the user should also be validated by php or similar.

Edited by BrowserBugs

  • Author

Quote
Edit: Forgot to say, as rbrtsmith says that java validation is great for visual prompt just not as a safeguard; whatever you need to validate from the user should also be validated by php or similar.

 

 

How should I add PHP that (not very well-versed, sorry!)?
I have joined the form to the external page contactus.php:
<?php

$formurl = "http://www.nialldevlin.com/contact.html" ;
$thankyouurl = "http://www.nialldevlin.com/thankyou.html" ;

$uself = 0;

$headersep = (!isset( $uself ) || ($uself == 0)) ? "\r\n" : "\n" ;
$name = $_POST['Name'] ;
$email = $_POST['Email'] ;
$telephone = $_POST['Telephone'] ;
$comments = $_POST['Comments'] ;

$http_referrer = getenv( "HTTP_REFERER" );

$subject = "[Greencastle Parish Website] New message from $name";

$comments =

	"This message was sent from:\n" .
	"$http_referrer\n" .
	"------------------------------------------------------------\n\n" .
	"Name: $name\n" .
	"Email: $email\n" .
	"Telephone: $telephone\n" .
	"------------------------ COMMENT(S) ----------------------\n\n" .
	$comments .
	"\n\n------------------------------------------------------------\n" ;

mail("nialldevlin@hotmail.com", $subject, $comments, "FROM: info@greencastleparish.com" . $headersep . "Reply-To: \"$name\" <$email>" . $headersep . "X-Mailer: chfeedback.php 2.07" );
header( "Location: $thankyouurl" );
exit ;

?>

 

Edited by Demonolith

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.