我正在尝试根据所选国家/地区验证电话号码字段。例如。 SG为8位数,美国为10位数。任何人都知道如何使用Jquery来做这件事?
这是我的代码(FORM):
<form id="form" action="http://localhost/formsubmitted.php" method="post">
<div>
<input type="text" name="name" id="name" placeholder="Name" required />
</div>
<div>
<select class="dropdown" id="country" name="gender" required >
<option value="" disabled selected>Country</option>
<option value="sg">Singapore</option>
<option value="usa">United States of America</option>
</select>
</div>
<div>
<input type="text" name="ssid" id="ssid" placeholder="SSID" required />
</div>
<div>
<input type="text" name="phone" id="phone" placeholder="Phone Number" required />
</div>
<input id="submit" class="button" type="submit" value="submit"/>
</form>
这是我的代码(JQUERY VALIDATION):
<script type="text/javascript">
$(document).ready(function() {
$('#submit').one('click', function() {
$('#form').validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 100,
letterspaces: true
},
ssid: {
required: true,
minlength: 8,
maxlength: 9,
nowhitespace: true
},
country: {
required: true,
},
phone: {
required: true,
minlength: 8,
maxlength: 11,
digits: true
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "Name should be more than 2 characters",
maxlength: "Name should be less than 100 characters",
letterspaces: "Name should contain only letters and spaces"
},
country:{
required: "Please select your country"
},
ssid: {
required: "Please enter your SSID",
minlength: "SSID should be more than 8 characters",
maxlength: "SSID should be less than 9 characters",
nowhitespace: "SSID should not have any spaces"
},
phone: {
required: "Please enter your mobile number",
minlength: "Mobile number should be more than 8 characters",
maxlength: "Mobile number should be less than 11 characters",
digits: "Mobile number should contain only digits"
},
},
});
$("#submit").click(function(){
$("#form").submit();
if (validationIsTrue()) {
return true;
}
else {
return false;
}
});
});
});
</script>
答案 0 :(得分:6)
我为您的验证创建了Demo取决于具有以下代码的其他字段:
$("#contact").validate({
rules: {
"name-contact": {
required: true
},
"test":{
required:true
},
"phone":{
required:true,
minlength: function(element){
if($("#test").val()==1){
return 3;
}
else if($("#test").val()==2){
return 5;
}
else{
return 1;
}
}
}
},
messages: {
"name-contact": {
required: "Please, enter a name"
},
"test": {
required: "Please, enter"
},
"phone":{
minlength:"minlenght"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
alert($("#test").val());
return false; // for demo
}
});
您可以在代码中使用此逻辑。希望这对你有帮助。
答案 1 :(得分:1)
使用jQuery Code
添加此代码。
jQuery('#country').change(function(){
var selected = jQuery(this).find(":selected").val();
if(selected == 'sg')
{
jQuery('#phone').attr('maxlength', '8');
} else if(selected == 'usa') {
jQuery('#phone').attr('maxlength', '10');
}
});
希望这会对你有帮助......