I have a simple form that needed validation.
I did this with the empty()
function. If the validation doesn't pass it gives the user an alert. As soon as this alert is created all entered values are gone.
I would like to keep them.
This is what I did:
<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
<table>
<tr>
<td>
Name:<input type="text" id="name" name="name">
</td>
</tr>
<tr>
<td>
<input class="submit-button" type="submit" value="Send" name="submit">
</td>
</tr>
</table>
</form>
<?php
if($_POST["submit"]){
if (!empty ($_POST["name"])){
// do something
}else{
?>
<script type="text/javascript">
alert('U heeft niet alle velden ingevuld. Graag een volledig ingevuld formulier versturen');
</script>
<?php
}
?>
Bizarrely I happen to be working on a similar thing and have been using the following to ensre that form data is available after submission of the form. It uses a session variable to store the results of the POST and is used as the value in the form field.
/* Store form values in session var */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
foreach( $_POST as $field => $value ) $_SESSION[ 'formfields' ][ $field ]=$value;
}
/* Function used in html - provides previous value or empty string */
function fieldvalue( $field=false ){
return ( $field && !empty( $field ) && isset( $_SESSION[ 'formfields' ] ) && array_key_exists( $field, $_SESSION[ 'formfields' ] ) ) ? $_SESSION[ 'formfields' ][ $field ] : '';
}
/* example */
echo "<input type='text' id='username' name='username' value='".fieldvalue('username')."' />";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With