tags:

views:

100

answers:

4

how can i prevent a form to be submitted when it only contains a space? for example a user presses the space bar on a field, the space will be considered as a character so the forms submits. how can i prevent that in php?

+5  A: 

For PHP - Server-side validation (After the form is submitted)

A combination of trim() and empty() will return true if passed a string with only a space.

$a = ' ';
$a = trim($a);
if (empty($a)) print 'Empty!'; // Empty!

Sidenote: Under normal circumstances, it's always a good idea to trim() user-input.

For Javascript - Client-side validation (Before the form is submitted)

Use the onSubmit event to fire a validate function:

<form onSubmit="validate()">
  <input type="text" id="myInput" />
  <input type="submit" value="submit" />
</form>

<script type="text/javascript">
function validate() {
  myInput = document.getElementById('myInput');
  if (myInput.value.match(/^s+$/) || myInput.value == '') {
    alert('No Empty Values!');
    return false;
  }
}
</script>
Mike B
At my firm, we consider it "good practice" to validate both via client and server. Just a thought.
Plan B
+2  A: 

Use trim() and then test against null values.

Mike B presents a good point. You could prevent the form from actually being submitted with Javascript. If you rely on PHP, the form will be submitted, but you could present the same form to the user with an error message.

Evan Meagher
test against null? Shouldn't you test against an empty string? Yes `"" == null`, but `"" === ""`!
nickf
A: 

HTML:

<form onsubmit="return validate(this);">

Javascript:

function validate(form) {
    ok = true;
    for (var i = 0, il = form.elements.length; i < il; ++i) {
        form.elements[i].value = form.elements[i].value
                                    .replace(/^\s\s*/, '')
                                    .replace(/\s\s*$/, '');
        ok &= !!form.elements[i].value;
    }
    if (!ok) alert("Oh hey - type something in these boxes, k?");
    return ok;
}

PHP:

$myVar = trim($_POST['myFormVariable']);
if (!$myVar) {
    echo "Oh hey, you should type something.";
} else {
    doStuff();
}
nickf
`\s\s*` == `\s+`. Also, why not just `form.elements[i].value = form.elements[i].value.replace(/^\s+|\s+$/g, '');`?
Justin Johnson
because that's much slower. The regex has to parse the entire string, instead of the just the first (and last) chars which are spaces. See [this article which benchmarks 11 different types of trim function](http://blog.stevenlevithan.com/archives/faster-trim-javascript). Note specifically the difference between functions 1 and 2 (I used #1 above). `\s+` is actually slower than `\s\s*`
nickf
A: 

Once your forms get more complex Jquery has a wonderful plugin for this called validate that provides extensive form validation.

+1 to Plan B. Always validate the same input again in php as there is nothing stopping a user from just creating his own form and submitting it to your page.

Daren Schwenke