gpt4 book ai didi

基于另一个字段的 JQUERY 验证

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:17 24 4
gpt4 key购买 nike

我正在尝试根据所选国家/地区验证电话号码字段。例如。 SG 将是 8 位数字,USA 将是 10 位数字。任何人都知道我如何使用 Jquery 来完成它?

这是我的代码(表格):

    <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 验证):

<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>

最佳答案

我创建了一个 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
}
});

您可以简单地将此逻辑与您的代码一起使用。希望这对您有所帮助。

关于基于另一个字段的 JQUERY 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952147/

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