开发者

PHP form validation error messages placement

开发者 https://www.devze.com 2023-03-08 08:39 出处:网络
Is it possible to place error messages resulted from form validation inside the form, using PHP/XHT开发者_运维知识库ML/CSS only?You can put error messages anywhere on the site you wanted.It all depend

Is it possible to place error messages resulted from form validation inside the form, using PHP/XHT开发者_运维知识库ML/CSS only?


You can put error messages anywhere on the site you wanted. It all depends on where in your scripts you place your code to emit it.


One strategy I've seen used a lot in PHP Frameworks when AJAXy submissions are disabled is to have a field to display the error on the page, and then actually populate that field with the data if the page comes back with an error.
Such as:

<label for="field">Label"><input name="field" type="text" />
<?php if($_POST['errors_field']) echo '<p class="error">'.$errors['field'].'</p>'; ?>

This strategy would only show the <p> tag when the page input box has an error. This method of course involves returning a populated array of all errors to the page when it fails validation.


I would make 2 pages one with the form like this. We will call it form.php. Make sure your form method is "post", and you have named your inputs. create a div that will be used for error callback($error). You can place the Error var anywhere you want not just in the form.

<form method="post">
<input type="text" name="text">
<div><?php echo $error ?></div>
<input type="submit" name="submit">
</form>

Next Make another php page like this and include the form.php page at the bottom. set error as empty string first. See if the button is clicked(isset). If the field is equal to a empty string set the error($error). if no error Process the form. Hope this helps.

<?php
$error = '';
if(isset($_POST['submit'])){
if($_POST['text'] == ''){
$error = "Here is your Error inside the form."; 
} else {//"Sanitize and Process the Form"; 
}}
include 'form.php';
?>
0

精彩评论

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