我知道这个问题是一个非常简单的问题。我只需要付费来验证表单上的文本输入字段。我知道我可以使用HTML5的数字类型并查看了prey_replace但我不了解这个函数对我来说..
我在表单中验证输入字段的最佳方法是什么? PHP,JQuery,其他?只是想确保文本字段中插入的内容是00.00之类的货币格式(我已将文本输入的最大长度设置为5)我现在只需要检查以确保只有数字,数字和小数是唯一的东西表格提交时提交..
这对我所需要的东西来说可能有点过分,但我确实从另一个问题中找到了这个小提琴:http://jsfiddle.net/vY39r/11/但是我无法让它发挥作用,我确保名称匹配。
以下是我所拥有的基本示例:
<form name="setPrices" action="" method="POST">
<fieldset>
<label for="lowPrice">Low Resolution:</label>
<input type="text" class="price" id="lowPrice" name="lowPrice" value="<?php echo $low_price; ?>" maxlength="5" />
</fieldset>
<fieldset>
<label for="mediumPrice">Medium Resolution:</label>
<input type="text" class="price" id="mediumPrice" name="mediumPrice" value="<?php echo $medium_price; ?>" maxlength="5" />
</fieldset>
<fieldset>
<label for="highPrice">High Resolution:</label>
<input type="text" class="price" id="highPrice" name="highPrice" value="<?php echo $high_price; ?>" maxlength="5" />
</fieldset>
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit" id="submit" class="button">Save</button>
</form>
答案 0 :(得分:3)
<?php
$_POST['lowPrice']=preg_replace('/[^0-9\.\-]+/','',$_POST['lowPrice']);
//...
?>
编辑:为了清晰起见,将你的P在lowPrice中大写......
答案 1 :(得分:3)
您可以使用正则表达式^[0-9]+(\.[0-9]{2})?$
来检查输入是否为货币格式。
您可以在php中使用以下代码来检查输入是否与上述正则表达式匹配:
if (preg_match('/^[0-9]+(\.[0-9]{2})?$/', $_POST['lowPrice'])) {
# Successful match
} else {
# Match attempt failed
}
对于检查输入是否为货币格式所需的所有验证执行此操作。
正则表达式的描述如下:
^ : Assert position at the beginning of the string
[0-9]+ : Match a single character in the range between "0" and "9"
+ : Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(\.[0-9]{2})? : Match the regular expression below and capture its match into backreference number 1
? : Between zero and one times, as many times as possible, giving back as needed (greedy)
\. : Match the character "." literally
[0-9]{2} : Match a single character in the range between "0" and "9"
{2} : Exactly 2 times
$ : Assert position at the end of the string (or before the line break at the end of the string, if any)