现有一张使用文本提示框的报表。用户希望在文本框中以nnnn-nnnnnnnn的格式输入提示。
此例,我们一起编写一个脚本用来验证用户输入的内容是否符合格式要求。如果符合要求,则提交报表。
准备工作…
任创建一张使用textbox prompt的报表。
如何实施…
1. 在textbox外,嵌套上一个span标签,并命名其ID为A1。
2. 在页脚添加如下脚本:
<script>
function ValidatePage()
{
var theSpan = document.getElementById("A1");
var a = theSpan.getElementsByTagName("input"); /* this captures the textbox */
for( var i = a.length-1; i >= 0; i-- )
{
var link = a[i];
if( link.id.match(/PRMT_TB_/))
{phoneRegex = /^\d{4}-\d{8}$/; /* This is regular expression to allow only the strings in (nnn) nnn-nnnn format */
if( !link.value.match( phoneRegex ) ) {
alert( 'Please enter phone number in nnnn-nnnnnnnn format' );
link.focus();
link.select();
return; }
else {promptButtonFinish();}
}
}
}
/* Below is standard code to get FormWarpRequest*/
var fW = (typeof getFormWarpRequest == "function" ? getFormWarpRequest() : document.forms["formWarpRequest"]);
if ( !fW || fW == undefined) { fW = ( formWarpRequest_THIS_ ? formWarpRequest_THIS_ : formWarpRequest_NS_ );}
/* This returns all elements of Button tag */
var buttons = fW.getElementsByTagName("BUTTON");
for (var i=0; i<buttons.length; i++)
{
if (buttons[i].id.match(/finish/)) // Capture the finish button
{
if (buttons[i].onclick.toString().indexOf('finish') > 0)
{ buttons[i].onclick = ValidatePage;} /* This overrides the FINISH button and attaches it to our function */
}
}
</script>
工作原理…
我们首先定义一个函数,用来俘获文本提示框输入的内容,并检查内容是否符合需要的格式。这里我们使用JavaScript的match函数,此函数允许我们使用正则表达式解析文本字符串。正则表达式^\d{4}-\d{8}$仅仅允许格式为nnnn-nnnnnnnn的字符串。如果你想学习和验证更多和正则表达式相关的内容,请参考网站:
http://www.regular-expressions.info/javascriptexample.html
如果输入内容和正则表达式相符,我们调用promptButtonFinish()方法提交报表;如果不符合,页面会弹出一个警告信息,并将光标移动到文本框中。
脚本的第二部分,用重写OnClick事件的方法把ValidatePage()函数添加到Finish按钮。