开发者

how to eliminate space in forms in php

how can i prevent a form to be submitted when it only contains a space? for开发者_Go百科 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?


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>


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.


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();
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜