在Joomla! 1.5中可以JHTMLBehavior::formvalidation()这一函数进行表单数据验证,这一函数,引入基于mootools的 validate.js ,文件在 media/system/js 目录下。
在引入了validate.js后,只要设置form 的class 就可以对表单进行验证,下面是实例代码:
<?php JHTMLBehavior::formvalidation(); ?> <script language="javascript"> function myValidate(f) { if (document.formvalidator.isValid(f)) { f.check.value='<?=JUtility::getToken()?>';//send token return true; } else { alert('Some values are not acceptable. Please retry.'); } return false; } </script> <form id="WV-form" method="post" class="form-validate" onSubmit="return myValidate(this);"> <input type="hidden" name="check" value="post"/> ... <input type="text" name="email" size="30" class="required validate-email"/> ... <input type="submit" value="Submit" /> </form>
这段代码只是对email输入字段进行验证,我们需要设置 form的class 为 form-validate,同时设置email输入class为 required validate-email ,如果某一输入不需要验证,可以设置class为 invalid
$jAp=& JFactory::getApplication(); if ($_POST['check']!=JUtility::getToken()) { //First verify if by a javascript error or other possibilities the form has not been submitted without the validation if ($_POST['check']=='post') $jAp->enqueueMessage('Please check all the fields of the form, aub.<br/> If your browser blocks javascript, then this form will never be succesfull. This is a security measure.','error'); //If then still the check isn't a valid token, do nothing as this might be a spoof attack or other invalid form submission return false; }
以上代码是服务器接收数据,进行几种验证。
Custom handlers
If you want a custome handler, you can add one to the class, as follow example (defined AFTER the validate.js):
Window.onDomReady<span class="br0">(</span><span class="kw2">function</span><span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> document.formvalidator.setHandler<span class="br0">(</span><span class="st0">'birth'</span>, <span class="kw2">function</span><span class="br0">(</span>value<span class="br0">)</span> <span class="br0">{</span> regex=/^\d<span class="br0">{</span><span class="nu0">4</span><span class="br0">}</span><span class="br0">(</span>-\d<span class="br0">{</span><span class="nu0">2</span><span class="br0">}</span><span class="br0">)</span><span class="br0">{</span><span class="nu0">2</span><span class="br0">}</span>$/; <span class="kw1">return</span> regex.test<span class="br0">(</span>value<span class="br0">)</span>; <span class="br0">}</span><span class="br0">)</span> <span class="br0">}</span><span class="br0">)</span>
You can then set any class to validate-birth to make it validate as yyyy-mm-dd. (Valid date is not checked!)
相关文章



