简体   繁体   English

不使用正则表达式的 PHP 验证表单

[英]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.我使用 HTML 表单,然后将其发送到我的 php 脚本,在那里我应该检查来自 html 表单的值是否为十进制。 If not, php should print it using echo with red font-color and if it's correct with standard black font..如果没有,php 应该使用带有红色字体颜色的 echo 打印它,如果使用标准黑色字体是正确的..

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.第一种方法只是将值与自身的floor()版本进行比较。

Alternatively, checks to see if the value is_numeric() then checks if the string has a decimal.或者,检查值是否为is_numeric()然后检查字符串是否有小数。

Edit: Changed the second method from substr() to substr_count() as @ArtisticPhoenix suggested as there may be the possibility of >= two decimals.编辑:按照@ArtisticPhoenix 的建议,将第二种方法从substr()更改为substr_count()因为可能存在 >= 两位小数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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