gpt4 book ai didi

javascript - 使用带有一些自定义函数的 jquery 验证名称

转载 作者:行者123 更新时间:2023-11-30 10:27:20 24 4
gpt4 key购买 nike

我正在使用 jQuery 进行简单的表单验证

事实上,我使用 jQuery 插件来验证电子邮件地址字段,现在我想对 name 字段进行单独验证我也试过了,但它不起作用,我无法找出问题所在在后面。

<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and an email address.</title>

<link rel="stylesheet" href="main.css" type="text/css" />
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script>
$(function() {
$( "#myform" ).validate({
rules: {
name: {
required: true,
minlength: 4,
maxlength: 20,
customvalidation: true
}
},
messages: {
name: {
required: "Dude, enter a name",
minlength: $.format("Keep typing, at least {0} characters required!"),
maxlength: $.format("Whoa! Maximum {0} characters allowed!")
}
}
});
$.validator.addMethod("customvalidation",
function(value, element) {
return /^[A-Za-z\d=#$%@_ -]+$/.test(value);
},
"Sorry, no special characters allowed"
);
});
</script>
</head>

<body>
<div id="navbar">
<ul id="nav">
<li><a id="clickBack" href="backPage.htm">clickBack</a></li>
<li><a id="clickForward" href="forwardPage.htm">goForward</a></li>
</ul>
</div><br><br>
<label for="field"> Name: </label>
<input class="left" id="name" name="name" minlength="4" class="required name"/>
<br/>
<form id="myform" method="post" action="">
<label for="field">Email: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Submit">
</form>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});

</script>

</body>
</html>

需要一些指导...谢谢。

最佳答案

尝试使用这个最好的 JQuery 验证 plugin

username: {
required: true,
minlength: 2
},

messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},

如果你想要自定义验证,你可以试试这个:

 $.validator.addMethod("customvalidation", function(value, element) {
return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
}, "Username must contain only letters, numbers, or dashes.");

关于javascript - 使用带有一些自定义函数的 jquery 验证名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18958822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com