javascript — проверка формы jQuery и проблема с отправкой

У меня есть следующая форма, которая использует jQuery для проверки формы и отправки, если все поля заполнены правильно. До сих пор все работает нормально. Но я хочу добавить следующее, но не понимаю, как это сделать (так как я новичок в jQuery).

  1. Текстовые поля (как имя & фамилия) не должен принимать любое число.

Как я могу добавить их в свой код? Пожалуйста помоги.

Вот мой код

<?php
include'includes/db.php';
if(isset($_POST['submit']))
{
$fname =(!empty($_POST['firstname']))?$_POST['firstname']:null;
$lname =(!empty($_POST['lastname']))?$_POST['lastname']:null;
$email =(!empty($_POST['email']))?$_POST['email']:null;
$mobile =(!empty($_POST['mobile']))?$_POST['mobile']:null;
$dob =(!empty($_POST['dob']))?$_POST['dob']:null;
$location =(!empty($_POST['location']))?$_POST['location']:null;
$state =(!empty($_POST['state']))?$_POST['state']:null;
$gender =(!empty($_POST['gender']))?$_POST['gender']:null;

$str = "INSERT INTO members(mem_fname, mem_lname, mem_email, mem_mobile, mem_dob, mem_location, mem_state, mem_gender)VALUES('$fname', '$lname', '$email', '$mobile', '$dob', '$location', '$state', '$gender')";
$sql = mysql_query($str);

if($sql){
echo "Data Inserted Successfully";
}else{
echo "Data insertion failed";
}
}
?>

<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( ".datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
$("#register-form").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
mobile: {
required: true,
minlength: 10,

},
dob: "required",
location: "required",
state: "required",
gender: "required",
agree: "required"},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
mobile: {
required: "Please provide your mobile number",
minlength: "Your mobile number must be 10 characters long"},
email: "Please enter a valid email address",
dob: "Please provide you Date of Birth",
location: "Please provide your location",
state: "Please provide your state",
gender: "Please provide your gender",
agree: "Please accept our terms of service"},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
</head>
<body>
<br />
<br />
<form action="" method="post" id="register-form" novalidate="novalidate">
<div class="label">First Name</div>
<input type="text" id="firstname" name="firstname" />
<br />
<div class="label">Last Name</div>
<input type="text" id="lastname" name="lastname" />
<br />
<div class="label">Email</div>
<input type="email" id="email" name="email" />
<br />
<div class="label">Mobile</div>
<input type="number" name="mobile" id="mobile" />
<br />
<div class="label">DOB</div>
<input type="text" name="dob" id="dob" class="datepicker"/>
<br />
<div class="label">Location</div>
<input type="text" name="location" id="location" />
<br />
<div class="label">State</div>
<input type="text" name="state" id="state" />
<br />
<div class="label">Gender</div>
<input type="radio" name="gender" id="gender" value="male" />
Male
<input type="radio" name="gender" id="gender" value="female" />
Female<br />
<div>
<br />
<input type="checkbox" name="agree" id="mobile" />
&nbsp;Do You accept our terms of service?<br />
<br />
<div>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>

0

Решение

Вы можете использовать шаблонное правило из файла Additional-method.js из jquery-validate

$("#register-form").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
mobile: {
required: true,
minlength: 10,
pattern: /^[789]/
},
dob: "required",
location: "required",
state: "required",
gender: "required",
agree: "required"},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
mobile: {
required: "Please provide your mobile number",
minlength: "Your mobile number must be 10 characters long",
pattern: 'should start with 7,8 or 9'
},
email: "Please enter a valid email address",
dob: "Please provide you Date of Birth",
location: "Please provide your location",
state: "Please provide your state",
gender: "Please provide your gender",
agree: "Please accept our terms of service"},
submitHandler: function (form) {
form.submit();
}
});

Демо-версия: скрипка

1

Другие решения

Вам нужно добавить новые методы, такие как этот:

jQuery.validator.addMethod("checkMobileNumberFirst", function(value, element) {
firstNumber = value.substring(0,1);

if (firstNumber <= 9 && firstNumber >=7  ){
return true;
}else{
return false;
}
}, "The Mobile phone number has to start with 7, 8 or 9");

и затем добавьте новый метод в вашу проверку:

        mobile: {
required: true,
minlength: 10,
checkMobileNumberFirst: true
},
0

http://jqueryvalidation.org/ эта ссылка. он содержит плагин проверки jquery и демонстрацию.

0
По вопросам рекламы [email protected]