Nienke
Nienke

Reputation: 23

php input form can only be numbers not words

i made a form where you can put a number and show which one is the highest. i want to make sure you can put any words in this form. that there show a notification you cant put words in the form

<?php

function maxGetal($getal1, $getal2)
{
    if ($getal1 > $getal2) {
        return ($getal1);
    } elseif ($getal2 > $getal1) {
        return ($getal2);
    } else {
        return ("gelijk");
    }
}



?>
<form action="" method="post">
    <input type="text" name="eerstegetal" placeholder="Eerste getal"><br>
    <input type="text" name="tweedegetal" placeholder="Tweede getal"><br>
    <input type="submit" name="submit" value="Bereken hoogste getal">
    <p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
    $maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
    echo $maxgetal;
}

$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);


?>

Upvotes: 1

Views: 45

Answers (2)

D. Dimopoulos
D. Dimopoulos

Reputation: 315

The following code shows a notification when a letter is typed.

<?php

function maxGetal($getal1, $getal2)
{
    if ($getal1 > $getal2) {
        return ($getal1);
    } elseif ($getal2 > $getal1) {
        return ($getal2);
    } else {
        return ("gelijk");
    }
}



?>

<form action="" method="post">
    <input type="text" id="eerstegetal" name="eerstegetal" oninput="Eerste_check()" placeholder="Eerste getal"><br>
    <input type="text" id="tweedegetal" name="tweedegetal" oninput="Tweede_check()" placeholder="Tweede getal"><br>
    <input type="submit" name="submit" value="Bereken hoogste getal">
    <p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
    $maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
    echo $maxgetal;
}

$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);


?>

<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>

<script>
    function Eerste_check(){
        var eerstegetal = $('#eerstegetal').val()

        var pattern = /^\d+\.?\d*$/;
        if(!pattern.test(eerstegetal)){
            alert('Eerstegetal should contain only numbers.')
        }
    }

    function Tweede_check(){
        var tweedegetal = $('#eerstegetal').val()

        var pattern = /^\d+\.?\d*$/;
        if(!pattern.test(tweedegetal)){
            alert('Tweedegetal should contain only numbers.')
        }
    }
</script>

Upvotes: 1

D. Dimopoulos
D. Dimopoulos

Reputation: 315

Try the following:

    <input type="number" name="eerstegetal" placeholder="Eerste getal"><br>
    <input type="number" name="tweedegetal" placeholder="Tweede getal"><br>

I hope it helps

Upvotes: 0

Related Questions