我正在尝试验证带有标题(例如Mr,Mrs,Ms ..)的下拉菜单,因此我需要将此字段作为必填字段,如果未选择标题,则显示错误消息。
我能够通过在jquery的“规则”部分中使用它们的名称属性来验证所有其他字段(即输入),并显示我想要的消息。
但是对于标题字段,名称atribute不能像输入一样起作用,我找不到解决方案。
是否有解决此问题的见解? 谢谢
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="diabetestool.css">
<title>Zedland Health Authority diabetes tool Contact form</title>
</head>
<body>
<header>
<h1>Zedland Health Authority<br>Contact Us</h1>
</header>
<main >
<form id="contactForm">
<div id="left">
<fieldset id="title_field">
<label for="title">Title*</label>
<p class="donotdisplay" id="titleMessage">Select a Title</p>
<select name="title" id="title">
<option value="-1">Please select your Title</option>
<option value="mr">Mr.</option>
<option value="ms">Ms.</option>
<option value="mrs">Mrs</option>
<option value="miss">Miss</option>
<option value="master">Master</option>
</select> <span class="error">title</span>
</fieldset>
//
$(function() {
$("#contactForm").validate ({
rules: {
title:{
required: true,
},
fname: {
lettersonly:true,
required: true,
minlength: 2,
},
sname:{
required: true,
pattern: /^[a-zA-Z\-]+$/i,
},
han:{
required: true,
pattern: /^ZHA\d{6}/,
},
email:{
required: true,
email: true,
},
tnumber:{
required: false,
pattern: /^[0-9]\d{10}/
}
},
messages: {
title:{
required: "This field is required. Please select a title."
},
fname: {
required: "This field is required. Please enter your first name.",
lettersonly: "Please enter only letters." ,
minlength: "First name must be at least two characters long."
},
sname: {
required: "This field is required. Please enter a valid Surname.",
pattern: "Please enter a valid surname. Use only letters and if necessary, an hyphen (-).",
},
email:{
required: "This field is required. Please enter a valid email address.",
},
han:{
required: "This field is required. Please enter a valid Zedland Health Authority number.",
pattern: "Your ZHA number should contain the characters ZHA (case sensitive), followed by six digits.",
},
tnumber:{
pattern: "Please a valid UK telephone number."
},
},
},
)},
)
答案 0 :(得分:2)
只需从您的第一个选项中删除“ -1”值,即可解决您的验证问题
<select name="title" id="title">
<option value="">Please select your Title</option>
<option value="mr">Mr.</option>
<option value="ms">Ms.</option>
<option value="mrs">Mrs</option>
<option value="miss">Miss</option>
<option value="master">Master</option>
</select>
答案 1 :(得分:1)
只需从值属性中删除-1。
testmongodb