简体   繁体   中英

PHP Validation form without using a regex

Im working with HTML form, then I send it to my php script, where I should check if a value from html form it's decimal. If not, php should print it using echo with red font-color and if it's correct with standard black font..

First of all, I CAN'T use regex, to check if it's formally valid. Any clue?

There's a couple of ways this could be achieved:

<?php
$values = [
    '1',
    '1.1',
    '.11',
    'foo'
];

foreach( $values as $value ){
    if( $value > floor($value) ){
        echo '<p>is decimal</p>';
    }else{
        echo '<p style="color:red">not decimal</p>';
    }
}

echo '<hr>';

foreach( $values as $value ){
    if( is_numeric($value) && (1 === substr_count($value, '.')) ){
        echo '<p>is decimal</p>';
    }else{
        echo '<p style="color:red">not decimal</p>';
    }
}

The first way just compares the value against a floor() -ed version of itself.

Alternatively, checks to see if the value is_numeric() then checks if the string has a decimal.

Edit: Changed the second method from substr() to substr_count() as @ArtisticPhoenix suggested as there may be the possibility of >= two decimals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM