如何防止用户使用 jquery 验证插件在 html 输入框中输入零作为第一位数字,
How prevent user to enter Zero as first digit in html input box using jquery Validation plug-in,
我正在使用 J query Validate 插件验证 HTML 表单,我想限制一些东西,以便用户不能输入零作为第一位数字。
例如:我有一个文本框可以为任何项目输入金额,因此用户不能输入零作为金额。
您可以使用 addMethod
添加您自己的验证器来执行自定义验证
如要限制用户在文本字段中输入 0 作为第一个数字,可以使用正则表达式 ^[^0]\d*
.
来实现
这是一个片段。
$.validator.addMethod("pattern", function(value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid value.");
$("form").validate({
rules: {
cost: {
required: true,
//change regexp to suit your needs
pattern: /^[^0]\d*$/g
}
}
});
.form-group label.error {
color: maroon;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<form class="form-inline">
<div class="form-group">
<label for="cost">Cost:</span>
<input class="form-control" id="cost" type="number" name="cost">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</body>
</html>
我正在使用 J query Validate 插件验证 HTML 表单,我想限制一些东西,以便用户不能输入零作为第一位数字。
例如:我有一个文本框可以为任何项目输入金额,因此用户不能输入零作为金额。
您可以使用 addMethod
如要限制用户在文本字段中输入 0 作为第一个数字,可以使用正则表达式 ^[^0]\d*
.
这是一个片段。
$.validator.addMethod("pattern", function(value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid value.");
$("form").validate({
rules: {
cost: {
required: true,
//change regexp to suit your needs
pattern: /^[^0]\d*$/g
}
}
});
.form-group label.error {
color: maroon;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<form class="form-inline">
<div class="form-group">
<label for="cost">Cost:</span>
<input class="form-control" id="cost" type="number" name="cost">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</body>
</html>