大家好,我是一个新的PHP,我试图在表单上添加验证。我想要它,所以如果表格是空的,表格将不会提交。
<form id="form1" name="form1" method="post" action="category_created.php">
Enter a New Category Name :
<label for="cat"></label>
<input type="text" name="cat" id="cat" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
并将表单提交到将内容提交到数据库的文件中:
<?php
//category name received from 'new_category.php' is stored in cariable $cat
$cat=$_POST['cat'];
$qry=mysql_query("INSERT INTO category(category)VALUES('$cat')", $con);
if(!$qry)
{
die("There Was An Error!". mysql_error());
}
else
{
echo "<br/>";
echo "Topic ".$cat." Added Successfully";
echo "<br/>";
}
?>
任何帮助将不胜感激
感谢
答案 0 :(得分:0)
使用onsubmit
并验证如下
<form onsubmit="return validate()" id="form1" name="form1" method="post" action="category_created.php" >
.....
</form>
并在javascript中
<script>
function validate(){
if(document.getElementById('cat').value.length<1)
{
alert('Please enter the Category Name');
return false;
}
else
{
return true;
}
}
</script>
答案 1 :(得分:0)
或者您可以通过ajax提交表单,在db-file中检查字段是否为空,ifso回显错误消息并通过javascript打印。通过这样做,您可以按照您想要的方式设置所有样式:)