form表单提交电话号码非空和格式验证
处理逻辑:
为了确保用户输入的手机号码非空且格式正确,你可以使用JavaScript添加验证逻辑。手机号码通常为中国大陆手机号格式,即11位数字,以1开头,第二位是3-9之间的任意数字。
具体代码:
<form name="phoneForm" id="phoneForm" onsubmit="return validateForm()">
<div class="tcui-cells tcui-cells_form">
<div class="tcui-cell">
<div class="tcui-cell__hd">
<label class="tcui-label">手机号码</label>
</div>
<div class="tcui-cell__bd">
<input class="tcui-input" type="tel" name="tel" id="tel" maxlength="11" value="{$__UserInfo['tel']}" placeholder="{lang tom_tongcheng:phone_tel_msg}">
</div>
</div>
</div>
<div class="phone-prompt">
<div style="color: #00f;text-align:center">{lang tom_tongcheng:phone_prompt2}</div>
</div>
<section class="page_rgs">
<section class="btn-group">
<input type="hidden" name="formhash" value="{$formhash}">
<input type="button" class="tcui-btn tcui-btn_primary id_phone_form_btn tc-template__bg" value="{lang tom_tongcheng:phone_btn}" onclick="submitForm()">
</section>
</section>
</form>
<script>
function validateForm() {
var tel = document.getElementById('tel').value;
var phonePattern = /^1[3-9]\d{9}$/; // 手机号码正则表达式
if (tel === "") {
alert("手机号码不能为空!");
return false;
} else if (!phonePattern.test(tel)) {
alert("手机号码格式不正确!");
return false;
}
return true;
}
function submitForm() {
if (validateForm()) {
document.getElementById('phoneForm').submit();
}
}
</script>
onsubmit="return validateForm()"
: 当表单尝试提交时,调用 validateForm 函数进行验证。
提交按钮的 onclick 事件调用 submitForm
函数,而不是直接提交表单。这样可以在提交前进行验证。
扫码添加技术【解决问题】
专注企业网站建设、网站安全16年。
承接:企业网站建设、网站修改、网站改版、BUG修复、问题处理、二次开发、PSD转HTML、网站被黑、网站漏洞修复等。
专业解决各种疑难杂症,您有任何网站问题都可联系我们技术人员。
本文来自博客园,作者:黄文Rex,转载请注明原文链接:https://www.cnblogs.com/hwrex/p/18667100