javascript - JavaScript Web 表单中的条件验证
问题描述
我正在开发一个使用 JavaScript 进行验证的 Web 表单。这只是更大表格的一部分。
该表单有一个问题,询问用户是否有社会安全号码。(SocialSecurity 字段)它有两个单选按钮,一个是,一个不是。如果用户回答是,则另一个字段 (SSN) 变为可见。否则,它会保持隐藏状态。这部分实际上正在工作。(SSN 字段的显示/隐藏)
JS 需要做两件事。如果用户回答是,则 SSN 字段成为必填字段,并且必须验证它是否有 9 个整数。但是,如果用户回答“否”,则必须不再需要将保持隐藏的 SSN 字段。
我遇到的困难是,只有当用户回答是时才需要 SSN,并在这种情况下正确验证它。
这是代码:
<div class="field SocialSecurity">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_lb" class="EditingFormLabel">Do you have a Social Security Number?</span>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpsocialsecurity" class="EditingFormControlNestedControl editing-form-control-nested-control">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list" class="radio radio-list-vertical">
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0">As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1">Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</span>
</div></div>
<div class="field SSN">
<label id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_lb" class="EditingFormLabel" for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText">Social Security Number</label>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpssn" class="EditingFormControlNestedControl editing-form-control-nested-control">
<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" maxlength="9" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />
</div> </div>
$('.field.SocialSecurity input[type=radio]').on("change", function() {
switch ($(this).val()) {
case 'As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.':
$('.field.SSN').show();
$('.field.SSN input').focus();
break;
case 'Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.':
$('.field.SSN').hide();
break;
}
});
//Here is the SS format validation section
function validateSSN() {
if (!validateRequiredTextField('SSN', 'Social Security Number'))
return false;
var value = $('.field.SSN input').val();
if (!isInteger(value) ||
(value.length != 9) ||
(value == '000000000') ||
(value == '111111111') ||
(value == '222222222') ||
(value == '333333333') ||
(value == '444444444') ||
(value == '555555555') ||
(value == '666666666') ||
(value == '777777777') ||
(value == '888888888') ||
(value == '999999999') ||
(value == '123456789')) {
$('.field.SSN input').focus();
alert("Invalid: Social Security Number");
return false;
}
return true;
}
//overall form validation - section on SSN
function validateForm()
if (!validateSSN())
return false;
解决方案
Your sample code is way to messy to work with. I've created this demo to show you the basics of how I think you should go about this. Note that I have simplified your code and changed both field names and classnames for the purpose of this demo. If you choose to implement a solution such as this you will need to update code to use your own values accordingly. (see second snippet.)
Solution:
- Use the browser's native validation by adding
required
andpattern
attributes to the fields. A simple Rx pattern=[0-9]{9}
will take care of your 9 integer validation requirement. Remember to re-validate server-side after the form has been submitted. - Using JavaScript (/jQuery) listen for changes on the SocialSecurity field then set the SSN field's
disabled
attribute totrue
orfalse
to enable or disable it depending on the chosen SocialSecurity value. If you don't want the disabled SSN field to be visible you can have the JS hide its parent container. Note that so long as the field is given thedisabled
property it won't be validated or submitted regardless of whether its visible or not.
Woking demo:
$(function() {
var $ssn = $(".SSN");
//add and enable and disable custom event:
$ssn.on("enable", function() {
$(this).show().find("input").attr("disabled", false);
}).on("disable", function() {
$(this).hide().find("input").attr("disabled", true);
})
//set initial state to disabled:
$ssn.trigger("disable");
//listen for changes and change the $ssn state accordingly
$("input[name='havessn']").on("change", function() {
var val = $(this).val();
if (val === 'nope') {
$(".SSN").trigger("disable");
} else {
$(".SSN").trigger("enable");
}
})
});
input:required:valid {
border: green solid 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="field SocialSecurity">
<span>Do you have a Social Security Number?</span>
<div>
<label><input type="radio" name="havessn" value="yup" required="required" />As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<label><input type="radio" name="havessn" value="nope" required="required" />Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</div>
<div class="field SSN">
<label>Social Security Number <input name="ssn" type="text" required="required" length="9" pattern="[0-9]{9}" title="Please provide a 9 digit SSN" />
</label>
</div>
<input type="submit" />
</form>
Demo for your specific use-case with unwieldy classnames intact:
$(function() {
var $ssn = $(".SSN");
//add and enable and disable custom event:
$ssn.on("enable", function() {
$(this).show().find("input").attr("disabled", false);
}).on("disable", function() {
$(this).hide().find("input").attr("disabled", true);
})
//set initial state to disabled:
$ssn.trigger("disable");
//listen for changes and change the $ssn state accordingly
$("input[name='p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list']").on("change", function() {
var val = $(this).val();
if (val === "Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.") {
$(".SSN").trigger("disable");
} else {
$(".SSN").trigger("enable");
}
})
});
input:required:valid {
border: green solid 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field SocialSecurity">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_lb" class="EditingFormLabel">Do you have a Social Security Number?</span>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpsocialsecurity" class="EditingFormControlNestedControl editing-form-control-nested-control">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list" class="radio radio-list-vertical">
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" required="required" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0">As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" required="required" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1">Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</span>
</div></div>
<div class="field SSN">
<label id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_lb" class="EditingFormLabel" for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText">Social Security Number</label>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpssn" class="EditingFormControlNestedControl editing-form-control-nested-control">
<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" required="required" length="9" pattern="[0-9]{9}" title="Please provide a 9 digit SSN" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />
</div></div>
推荐阅读
- javascript - Javascript | MediaRecorder API - 桌面上录制的视频文件无法在移动设备上播放
- c# - wpf 向上绑定:绑定到嵌套 uiElement 内的视图模型属性
- javascript - 在 P5JS 中访问类属性总是返回 false
- swift - Xcode 不显示测试涵盖的内容
- google-app-engine - 创建凭据时重定向 uri
- android - 更新房间中的多个项目,如何?
- oracle - 无法在 CHECK CONSTRAINT 中引用自定义函数
- reactjs - 为什么显示猫鼬:验证错误
- c# - 磁铁通电像地铁冲浪者一样不工作
- php - 使用 domelement 中的所有子节点更改节点值