我具有焦点/模糊功能,该功能在focus
上禁用提交按钮,然后在blur
上检查值是否与原始值不同(我将原始值保留在现有记录的data属性中)并检查是否为有效。但是我注意到一种情况,我的代码被破坏了。例如,在我的示例中,如果您输入07AB
,则代码函数将返回false,并且您将看到消息Code already exist.
。然后,如果我输入07ab
(只输入了小写a
和b
的代码值),则不会触发函数,用户可以提交表单。我确实使用过console.log()
来检查模糊函数中的语句,并且似乎checkValidty()
为true
返回了07AB
但为false
返回了07ab
。这是代码示例:
var codes = ["07AB","110A","117B","0316"]
$(".check-value").focus(function() {
var submitBtn = $(this).closest("form").find(":submit").prop("disabled", true); //Disable submit button on field focus.
}).blur(function() {
var fldObj = $(this),
frmMessage = $(this).closest("form").find(".message-submit"),
submitBtn = $(this).closest("form").find(":submit");
if (String(fldObj.val()) !== String(fldObj.data("current")) && fldObj.get(0).checkValidity()) {
console.log("Check value.");
if ($.inArray(fldObj.val(), codes) === -1) {
fldObj.get(0).setCustomValidity("");
} else {
fldObj.get(0).setCustomValidity("Code already exists!");
}
submitBtn.prop("disabled", false);
} else {
fldObj.get(0).setCustomValidity("");
submitBtn.prop("disabled", false);
}
});
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmSave" id="frmSave">
<div class="form-group required">
<label class="control-label" for="code"><span class="label label-primary">Code:</span></label>
<input type="text" class="form-control check-value" name="frm_code" id="frm_code" data-current="" data-fldname="code" maxlength="4" pattern="[a-zA-Z0-9]{1,4}$" title="Code field allows alphanumeric characters only (must be four characters length) - no other special characters"
placeholder="Example: 07AB" required>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div id="frm_message" class="alert message-submit"></div>
</div>
</div>
</form>
答案 0 :(得分:0)
小写字母和大写字母是具有不同ascii / utf / latin /等数字关联的不同字符。要解决您的问题,请使用正则表达式检查相等性,或在输入中使用.toLowerCase或.toUpperCase。
if ($.inArray(fldObj.val().toUpperCase(), codes) === -1) { //added toUpperCase()
fldObj.get(0).setCustomValidity("");
} else {
fldObj.get(0).setCustomValidity("Code already exists!");
}