我正在尝试使用jquery创建表单验证。首先,代码对我不起作用,其次我希望有一种更简单的方法来使用jquery来使用reg ex模式来验证我的表单。我不知道我是否正在使用jquery corectly,我想避免使用任何插件。
$(document).ready(function() {
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var pattern1 = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
var pattern2 = /[a-zA-Z]*( [a-zA-Z]*)?/;
$('#submit').on('click', function() {
var valid = true,
errorMessage = "",
if ($('#role').val() == '') {
errorMessage = "please choose a role \n";
valid = false;
}enter code here
if ($('#state').val() == '') {
errorMessage = "please choose a state \n";
valid = false;
}
if ($('#major').val() == '') {
errorMessage = "please provide a major \n";
valid = false;
}
if ($('#degree').val() == '') {
errorMessage = "please provide a degree \n";
valid = false;
}
if ($('#location').val() == '') {
errorMessage = "please choose a location \n";
valid = false;
}
if ($('#gradyear').val() == '') {
errorMessage = "please provide a graduation year \n";
valid = false;
}
if ($('#dept').val() == '') {
errorMessage = "please provide your department \n";
valid = false;
}
if ($('#campadd').val() == '') {
errorMessage += "please enter your address\n";
valid = false;
}
if($('#email').val() !== ""){
if(!pattern.test('#email'.val())){
errorMessage += "email invalid!\n";
valid = false;
}
if($('#telephone').val() !== ""){
if(!pattern1.test('#telephone'.val())){
errorMessage += "telephone number invalid!\n";
valid = false;
}
}}
if( !valid && errorMessage.length > 0){
alert(errorMessage);
}
答案 0 :(得分:0)
首先,你的帖子中的代码格式有点偏,这使得它有点难以阅读。当你说它“不起作用”时你究竟是什么意思?
我最好的猜测是,即使在出现errorMessage警告框之后,您的意思仍然是提交表单。如果是这种情况,那可能是因为您没有取消提交事件。
更改您的代码:
// submit instead of click event, give a name to the event argument
$('#submit').on('submit', function(e) {
//...
if( !valid && errorMessage.length > 0){
e.preventDefault(); // prevents the form submission
alert(errorMessage);
}