如何防止表单提交时没有必填字段?
我正在创建这样的表单元素:
$element = $this->CreateElement('select', 'countries');
$element->setLabel('Countries');
$element->setAttrib( 'required', true );
$element->addMultiOptions( array( ''=>'Select', '1'=>'Aus','2'=>'UK',.... ) );
以下代码正在提交表单:
// form
$form = new SomeForm();
// get request
$request = $this->getRequest();
// isPost
if( $request->isPost() ) {
// isValid
if( $form->isValid( $request->getPost() ) ) {
$values = $form->getValues();
// Save values into database here
} else {
$this->view->msg = "Required Fields are missing.";
}
} else {
$this->view->msg = 'Form is not submitted properly';
}
当我正确填写表单时,它会成功将记录保存到数据库中。但是当我不选择国家/地区时,它也会提交表格。我想我应该显示“必填字段缺失”。当缺少必填字段时,消息而不是将值插入数据库。
我缺少什么?
谢谢
I am creating forms elements like this:
$element = $this->CreateElement('select', 'countries');
$element->setLabel('Countries');
$element->setAttrib( 'required', true );
$element->addMultiOptions( array( ''=>'Select', '1'=>'Aus','2'=>'UK',.... ) );
Following code is submitting form:
// form
$form = new SomeForm();
// get request
$request = $this->getRequest();
// isPost
if( $request->isPost() ) {
// isValid
if( $form->isValid( $request->getPost() ) ) {
$values = $form->getValues();
// Save values into database here
} else {
$this->view->msg = "Required Fields are missing.";
}
} else {
$this->view->msg = 'Form is not submitted properly';
}
When I fill form properly then it save record into database successfully. But when I does not select country, it also submit form. I think I should show "Required Fields are missing." message instead of inserting values into database when required fields is missing.
What am I missing ??
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这一行:
并没有真正按照您的想法进行操作(它设置了 HTML 属性)。
您可能想要
(假设您正在使用 Zend_Form,从您发布的代码中并不完全清楚)。
This line:
doesn't really do what you think it does (it sets an HTML attribute).
You probably wanted
(This is assuming you're using Zend_Form, it's not totally clear from the code you posted).