View Full Version : php form validation with javascript

09-27-2011, 09:05 PM
could anyone tell me how to do this? i don't know anything about javascript, but it is the most elegant way to validate a form.

i have 2 questions asked in a form (name=questions). First question are radio buttons with 3 answers (name=answer). Second is a questions with a numeric value as answer with max 10 characters (name=questionb).

Could anyone tell me where to start?



09-27-2011, 11:30 PM
Perform server side validation as well. Anyone with some small hacking skills can send whatever they want to your server regardless of your client side validation. The client side validation is just a service to your visitors.

Having said that:
Use the onsubmit event on a form to perform validation. Return true if validation succeeds, false otherwise. Output something nice to the user to explain why validation fails.

You can also use the onkeypress event on form fields to limit input to certain characters. (However anything can be pasted into the field.)

Here's an example:
// This validates the whole form
var validateForm = function(form){
// collect errors in an array
var errors = [];
// check if any of the radiobuttons with the name "animals" are checks
var co = 0;
while(form.animals[co] && !form.animals[co].checked){co++};
!(form.animals[co] && form.animals[co].checked) && errors.push(
'Please check one of the animals.'
// Check that the number really is a number
(!form.number.value.length || form.number.value != form.number.value/1) && errors.push(
'Please enter a number.'
document.getElementById('formValidationErrors').innerHTML = errors.join('<br/>');
return false
else {
return true

// We can limit the input when the user writes something as well
var onlyAllowDigits = function(formEl){
var key=window.event?event.keyCode:e.which;
if(key<13){return true};
var keychar=String.fromCharCode(key);
var reg=new RegExp(/[0-9]/);
return reg.test(keychar)

<form onsubmit="return validateForm(this)" method="post" action="www.whatever.com/path">
The animal I like the most is:<br/>
<input type="radio" name="animals" id="a" value="dogs">&nbsp;<label for="a">dogs</label>
<input type="radio" name="animals" id="b" value="cats">&nbsp;<label for="b">cats</label>
<input type="radio" name="animals" id="c" value="rabbits">&nbsp;<label for="c">rabbits</label>
<label for="number">Enter a number (1-10 digits):</label><br/>
<input onkeypress="return onlyAllowDigits(this)" name="number" id="number" type="text" maxlength="10">
<input type="submit" value="Send">
<div id="formValidationErrors" style="color:#900"></div>