我有一个简单的单字段表单,要求输入域名:
<form name="domainForm" action="result.html" >
http://<input type="text" size="10" name="domain_name" id="domain_name">
<a href="javascript: validateDomain(domainForm);">Submit</a>
</form>
...并使用JS函数进行验证:
<Script type="text/javascript">
function validateDomain(the_form)
{
var the_domain = the_form.domain_name.value;
// strip off "http://" and/or "www."
the_domain = the_domain.replace("http://","");
the_domain = the_domain.replace("www.","");
var reg = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
if ( reg.test(the_domain) == false)
{
alert( "Please Enter a Valid Domain Name" );
the_form.domain_name.focus();
return false;
} // end if
} // end validateDomain()
</script>
但是,实时验证会很好。顺便说一句,我真的很想在POST方法中隐藏变量而不是GET,但AFAIK必须在使用JavaScript验证时使用GET。
非常感谢任何意见/建议!
答案 0 :(得分:1)
在输入上使用按键事件会在p
<form name="domainForm" action="" >
http://<input type="text" size="10" name="domain_name" id="domain_name">
<p class="rez"></p>
</form>
js -
$( "#domain_name" ).on('keypress',function() {
var the_domain = $(this).val();
// strip off "http://" and/or "www."
the_domain = the_domain.replace("http://","");
the_domain = the_domain.replace("www.","");
var reg = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
if ( reg.test(the_domain) == false)
{
$('#domain_name').focus();
$('.rez').text('Please Enter a Valid Domain Name');
} else { $('.rez').text('Valid Domain Name');}
});
jsfiddle:https://jsfiddle.net/Lzufkrw4/1/
答案 1 :(得分:0)
如果要实时验证,可以将处理程序绑定到输入的keyup事件,如
$('#domain_name').on('keyup', function(){
if(!validateDomain($(this).val())){
$('.rez').text('invalid domain')
}else{
$('.rez').text('valid domain')
}
});
同时将return true;
放在函数末尾,以便成功验证将返回true
function validateDomain(the_domain)
{
// strip off "http://" and/or "www."
the_domain = the_domain.replace("http://","");
the_domain = the_domain.replace("www.","");
var reg = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
return reg.test(the_domain);
} // end validateDomain()
将是我的建议