SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2005
    Location
    Manc, UK
    Posts
    72
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Validation of fields help

    Hi all,

    Im back for more advice. I am trying to figure out how I can doi the following - Its for an online form which will then be printed by the user. I need to ensure that nothing isnt completed on the form - I have been searching for a good tutorial on this but I can only seem to find ones that just include text boxes and the form will have a few dropdowns/select menus that need to be completed and I cant find much info on this. I wasnt sure whether to post in this section or php so I apologise if Im wrong.

    Hope someone can give me some advice.
    thansk in advance
    R

  2. #2
    Smart programmer silver trophy M.Zeb Khan's Avatar
    Join Date
    Jan 2004
    Location
    Luton, Beds
    Posts
    1,791
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by robvr6 View Post
    I need to ensure that nothing isnt completed on the form

    I couldn't get you on that, did you mean "nothing isn't incomplete" or what?

    Also, Could you post the form contents, like what fields/list etc will be in the form, and what kind of validation you want.

    Please tell us in a bit brief and we will try our best to help it out.

    Thanks

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    One way to do it is to assign class names that define validation parameters, then take action on them during validation.

    Code html4strict:
    <form id="myForm">
    <p><label>Name: <input type="text" name="name" class="required"></label></p>
    <p><select name="sex">
    	<option value="Choose sex" class="invalid">Choose sex...</option>
    	<option value="male">Male</option>
    	<option value="female">Female</option>
    	<option value="other">Other</option>
    </select></p>
    <p><input type="submit" name="submit"></p>
    </form>

    Code javascript:
    var myForm = document.getElementById('myForm');
    myForm.onsubmit = function () {
    var els = this.elements,
    	el,
    	i,
    	j,
    	classes,
    	validates = true;
    	for (i = 0; i < els.length; i += 1) {
    		el = els[i];
    		if (el.className > '') {
    			classes = el.className.split(' ');
    			for (j = 0; j < classes.length; j += 1) {
    				switch (classes[j].toLowerCase()) {
    				case 'required':
    					if (el.value.length === 0) {
    						alert(el.name + " can't be empty.\nPlease enter a value.");
    						validates = false;
    					}
    					break;
    				default:
    					break;
    				}
    			}
    		}
    		if (el.nodeName === 'SELECT') {
    			if (el.options[el.selectedIndex].className === 'invalid') {
    				alert(el.name + " has an invalid option.\nPlease choose another.");
    				validate = false;
    			}
    		}
    	}
    	return validates;
    };
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2005
    Location
    Manc, UK
    Posts
    72
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Thanks for replying. Yes I need to ensure all fields are completed. I am still waiting on the exact items that will be on the list but I believe there will be the usual name, address and contact details and about 20 yes/no dropdowns that the user needs to choose from.

    As for validation I just need the user to be prompted if a field is left blank or the select (yes/no) hasn't been completed.

    Hope thats made a bit more sense

    thanks

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Edit: added check for radio buttons
    Edit: use custom error handler to add error markers (*) and message to affected field
    Edit: after a failed submit, fields update their error status whenever they're changed

    Code css:
    .error {
    	color: red;
    }

    Code html4strict:
    <form id="myForm">
    <p><label>Name: <input type="text" name="name" class="required"></label></p>
    <p><select name="sex">
    	<option value="Choose sex" class="invalid">Choose sex...</option>
    	<option value="male">Male</option>
    	<option value="female">Female</option>
    	<option value="other">Other</option>
    </select></p>
    <p>Have you read the terms and conditions?
    	<label><input type="radio" name="terms" value="yes"> Yes</label>
    	<label><input type="radio" name="terms" value="no"> No</label>
    </p>
    <p><input type="submit" name="submit"></p>
    </form>

    The error handler adds error messages on to the affected fields.
    The clearError() function helps to tidy things up after someone has corrected an error.

    Code javascript:
    function validationError(el, message) {
    	var span,
    		text;
    	el = el.parentNode;
    	while (el.nodeName !== 'P') {
    		el = el.parentNode;
    	}
    	if (el.firstChild.className !== 'error') {
    		// create star
    		span = document.createElement('span');
    		text = document.createTextNode('*');
    		span.appendChild(text);
    		span.appendChild(document.createTextNode(' '));
    		span.className = 'error';
    		el.insertBefore(span, el.firstChild);
    		// create message
    		span = document.createElement('span');
    		span.appendChild(document.createTextNode(' '));
    		text = document.createTextNode(message);
    		span.appendChild(text);
    		span.className = 'error';
    		el.appendChild(span);
    	}
    }
    function clearError(el) {
    	el = el.parentNode;
    	while (el.nodeName !== 'P') {
    		el = el.parentNode;
    	}
    	if (el.firstChild.className === 'error') {
    		el.removeChild(el.firstChild);
    	}
    	if (el.lastChild.className === 'error') {
    		el.removeChild(el.lastChild);
    	}
    }

    These functions check for different types of validation errors

    Code javascript:
    function validateByClassName(el) {
    	var i,
    		classes,
    		validates = true;
    	if (el.className > '') {
    		classes = el.className.split(' ');
    		for (i = 0; i < classes.length; i += 1) {
    			if (classes[i].toLowerCase() === 'required') {
    				if (el.value.length === 0) {
    					validationError(el, ' Value is required.');
    					validates = false;
    				} else {
    					clearError(el);
    				}
    			}
    		}
    	}
    	return validates;
    }
    function validateSelectField(el) {
    	var validates = true;
    	if (el.options[el.selectedIndex].className === 'invalid') {
    		validationError(el, 'Invalid option, please choose another');
    		validates = false;
    	} else {
    		clearError(el);
    	}
    	return validates;
    }
    function validateRadios(el) {
    	var els = el.form.elements[el.name],
    		i,
    		validates = true;
    	el.form.isChecked[el.name] = false;
    	for (i = 0; i < els.length; i += 1) {
    		if (els[i].checked === true) {
    			el.form.isChecked[el.name] = true;
    		}
    	}
    	if (!el.form.isChecked[el.name]) {
    		validationError(el, 'Please select an option');
    		validates = false;
    	} else {
    		clearError(el);
    	}
    	return validates;
    }

    This code manages the validation functions and tells each element to update its error checking when they're changed.

    Code javascript:
    function setChangeFn(el, fn) {
    	el.onchange = function (el) {
    		return function () {
    			fn(el);
    		}
    	}(el);
    }
    var myForm = document.getElementById('myForm');
    myForm.onsubmit = function () {
    	var els = this.elements,
    		el,
    		i,
    		validates = true;
    	this.isChecked = [];
    	for (i = 0; i < els.length; i += 1) {
    		el = els[i];
    		validates = validateByClassName(el) && validates;
    		setChangeFn(el, validateByClassName);
    		if (el.nodeName === 'SELECT') {
    			validates = validateSelectField(el) && validates;
    			setChangeFn(el, validateSelectField);
    		} else if (el.type === 'radio') {
    			validates = validateRadios(el) && validates;
    			setChangeFn(el, validateRadios);
    		}
    	}
    	return validates;
    };
    Last edited by paul_wilkins; Aug 3, 2008 at 20:39.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •