1
votes

I have two text input fields (weight and height). User inputs values. I want it to work like this:

  • if the submitButton is not clicked: leave field empty
  • if the submitButton is pressed and user inputs non-integer: print "int"
  • if the submitButton is pressed and user inputs integer: keep the input visible

Validation is done, the point is to keep integer value visible in a field and text "int" if non-integer was provided until user inputs integers in both fields (and then clicks submitButton.

Forms:

<input type="text" name="height" value="<?=setValue( "height" )?>" size="4">
<input type="text" name="weight" value="<?=setValue1( "weight" )?>" size="4">

Conditions:

<?php
function setValue( $fieldName ) {
    if (!isset($_POST["submitButton"]))
        echo "";
    elseif ((isset($_POST["submitButton"]) && ( is_int(isset( $_POST[$fieldName] ) ))))
        echo $_POST[$fieldName];
    elseif ((isset($_POST["submitButton"]) && ( !is_int(isset( $_POST[$fieldName] ) ))))
        echo 'int';
}

function setValue1( $fieldName ) {
        if(!isset($_POST["submitButton"])) echo "";
    elseif ((isset($_POST["submitButton"]) && ( is_int(isset( $_POST[$fieldName] ) )))) 
        echo $_POST[$fieldName];
    elseif ((isset($_POST["submitButton"]) && ( !is_int(isset( $_POST[$fieldName] ) ))))
        echo "int";
}

Now when I input "1" in the height and press the submitButton I get "int" in both fields.

1
You need javascript for that, not php. And you should also look at html5 input types. - jeroen

1 Answers

0
votes

The easy way will be to validate the input using html5 'number' type.

Following example will only allow integers as input. However it may not work in all browsers:

<input type="number" name="height" id="height" />

And if you want to do using PHP, you need to validate it in the target file:

Form File:

<input type="text" name="height" id="height" size="4" />

Target file

if(is_int($_POST['height'])
      ...do something...