JavaScript Onclick电话/电子邮件验证功能不起作用



我有一个搜索字段,我希望用户能够通过电话或电子邮件进行搜索。但是,我的点击事件不会触发。我已经尝试了控制台工具,但似乎无法通过那里进行调试。

<body>  
</div>
<div style="text-align: center;">
{% from "_formhelpers.html" import render_field %}
<form method="POST"  action="/">
<dl style="display:inline-block">{{render_field(form.search)}}</dl> 
<button id="searchbutton" style="display:inline-block" type="submit"  class="btn btn-outline-success my-2 my-sm-0" onclick="doValidate()" >Search</button>
</form>
</div>  
<script>
function validateEmail(email) { //Validates the email address
var emailRegex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return emailRegex.test(email);
}
function validatePhone(phone) { //Validates the phone number
var phoneRegex = /^(+91-|+91|0)?d{10}$/; // Change this regex based on requirement
return phoneRegex.test(phone);
}
function doValidate() {
if (!validateEmail(document.appointment.requiredphone.value) || !validatePhone(document.appointment.requiredphone.value) ){
alert("Invalid Email");
return false;
}
}
</script>
{% endblock %}
</html>

该脚本在概念上有效,但是由于您没有包含呈现的标记,并且可能不包括一些相关的 javascript,因此很难确定您遇到的特定问题。

这个问题几乎可以肯定与代码中的这个 javascript 有关:

document.appointment.requiredphone.value

什么是appointment?什么是requiredphone?如果不知道HTML的结构,就不可能确定确切的问题。

因为您只包含{{render_field(form.search)}}而不是呈现的 HTML,所以这是我们所能提供的

工作片段
(使用document.getElementById和一些文本输入(

function validateEmail(email) { //Validates the email address
var emailRegex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return emailRegex.test(email);
}
function validatePhone(phone) { //Validates the phone number
var phoneRegex = /^(+91-|+91|0)?d{10}$/; // Change this regex based on requirement
return phoneRegex.test(phone);
}
function doValidate() {
if (!validateEmail(document.getElementById('email').value) || !validatePhone(document.getElementById('password').value)) {
alert("Invalid Email");
return false;
}
}
<div style="text-align: center;">
<form method="POST" action="/">
<dl style="display:inline-block"><input type="text" id="email"><input type="text" id="password"></dl>
<button id="searchbutton" style="display:inline-block" type="submit" class="btn btn-outline-success my-2 my-sm-0" onclick="doValidate()">Search</button>
</form>
</div>

问题可能是单击按钮时提交form。 尝试 event.preventDefault(( 来阻止表单提交操作

<button id="searchbutton" style="display:inline-block" type="submit"  class="btn btn-outline-success my-2 my-sm-0" onclick="doValidate(event)" >Search</button>
function doValidate(e) {
e.preventDefault(); // pass from button
console.log('here');
if (!validateEmail(document.appointment.requiredphone.value) || !validatePhone(document.appointment.requiredphone.value) ){
alert("Invalid Email");
return false;
}

最新更新