jquery - HTML - jQuery blur(function() 在输入时触发,然后循环
问题描述
我正在尝试验证两个电话号码。第一个电话号码验证工作正常;但是,如果第一个电话号码无效,然后我转到第二个电话号码,则在我输入任何数据之前触发第二个电话号码验证,并且我有一个循环“无效的电话号码 1c”,直到我关闭选项卡.
例如,我在第一个电话号码中输入“99999999”,然后在选项卡中输入。显示“请使用区号作为固定电话号码”的消息,然后显示“无效电话号码 1c”的连续循环。
如果我输入了无效的电话号码,然后转到另一个字段,而不是第二个电话号码,我只会收到一次错误消息(例如,在第一个电话号码中输入“99999999”,然后单击另一个文本输入字段,例如,状态)。
$("#telephone1").blur(function() {
validatePhoneNumber($(this).val(), this.id);
});
$("#telephone2").blur(function() {
validatePhoneNumber($(this).val(), this.id);
});
function validatePhoneNumber(phone_number, id) {
var formatted = "";
//remove all non-digits
phone_number = phone_number.replace(/\D/g, '');
//if number starts with 61, replace 61 with 0
if (phone_number.match(/^61/)) {
phone_number = "0" + phone_number.slice(2);
}
if (phone_number.match(/^04/)) {
if (phone_number.length === 10) {
var formatted = phone_number.replace(/(\d{4})(\d{3})(\d{3})/g, "$1 $2 $3");
} else {
alert('Invalid phone number 1a');
}
} else if (phone_number.match(/^02|03|07|08/)) {
if (phone_number.length === 10) {
var formatted = phone_number.replace(/(\d{2})(\d{4})(\d{4})/g, "($1) $2 $3");
} else {
alert('Invalid phone number 1b');
}
} else if (phone_number.length === 8) {
alert('Please use Area Code for landline numbers');
} else {
alert('Invalid phone number 1c');
}
//update
$('#' + id).val(formatted);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label for="telephone1" class="text-right col-lg-2 col-md-2 col-sm-2 col-xs-2 col-form-label">Telephone:</label>
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
<input type="text" id="telephone1" name="telephone1" placeholder="Telephone 1">
</div>
</div>
<div class="form-group row">
<label for="telephone2" class="text-right col-lg-2 col-md-2 col-sm-2 col-xs-2 col-form-label"></label>
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
<input type="text" id="telephone2" name="telephone2" placeholder="Telephone 2">
</div>
</div>
解决方案
我认为这只是alert
用于您的错误消息,onblur
用于您的验证和元素之间的选项卡的组合。onchange
如果根本没有输入任何值,我会建议使用或退出函数。这样您就不会收到垃圾邮件提醒。此外,blur
正如他们在文档中提到的那样,可以出于多种不同原因调用该事件,而change
当元素失去焦点时检查值的变化
推荐阅读
- html - Webpack 根据不同的 HTML 文件构建 HTML 页面
- python - AttributeError:“AxesSubplot”对象没有属性“Circle”在 tkinter 中嵌入 matplotlib
- sql - 如何编写没有连接的 SQL 查询?
- python - 使用正则表达式、正则表达式查找文本并返回列表
- vue.js - 运行 Vue 应用程序时出现错误“vue-cli-service: command not found”
- linux - 如何修复 Ubuntu 20.04 中的 Anaconda ProxyError?
- python - ThreadPoolExecutor executor.submit() 返回一个没有它就不会引发的异常
- javascript - 为对象本身设置获取函数或值 [Javascript]
- python - 批量运行aiohttp请求
- python - 下三角矩阵