我已经写了一个接受数字和特殊字符的验证,但是它只接受数字而不接受特殊字符。
$(document).ready(function () {
$("#law_degree_academic_years").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
<div class="form-group">
<label for="law_degree_academic_years" class="col-sm-2 control-label">41. Law Degree Academic Years</label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo $oppointArr['law_degree_academic_years'];?>" name="law_degree_academic_years" id="law_degree_academic_years" placeholder="Ex:2017-2020" minlegth="9" maxlength="9" required>
</div>
</div>
试试这个方法
function Validate() {
var isValid = false;
var regex = /^[0-9-+()]*$/;
isValid = regex.test(document.getElementById("TextBox1").value);
return isValid;
}
另一个可能的解决方案是为输入元素添加HTML5模式属性。
<input name="bla" type="text" pattern="[0-9-+()]*" placeholder="add something" required>
pattern属性使用给定的正则表达式执行验证,并将输入元素的状态设置为有效或无效。你不需要javascript来进行简单的测试。
更多信息:https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation