我正在使用webshim库,我需要比较两个文本字段值以避免重复,并希望设置自定义验证消息。
<form action="sample.html" method="post">
<label for="country1">Country 1 </label>
<input type="text" value="" id="country1" name="country1" required/>
<label for="country2">Country 2 </label>
<input type="text" value="" id="country2" name="country2" required />
<input type="button" value="submit" />
</form>
<script>
$(document).ready(function(){
$("#formsubmit").click(function(){
if($('form').checkValidity()){
if($("#country2").val()!= $("#country1").val()){
$("#country2").addClass('valid').removeClass('invalid')
$('form').submit();
}else{
$("#country2").addClass('invalid').removeClass('valid').setCustomValidity('Please Enter different country ');
}
}
});
});
</script>
如果两个文本字段值相同,则在Fist时间提交表单时,自定义有效性消息将按定义替换。但是当更改“国家2”值时,该字段仍然无效,表单未提交。
由于
答案 0 :(得分:0)
您的问题是,如果表单有效,您只需检查这些值。但是一旦添加自定义错误,您将永远无法提交。此外,您无需以编程方式提交表单。
在这里您可以找到一个working demo for your problem
var setCountryValidity = function () {
var message = 'Please Enter different country ';
//only test if valid or is invalid because of this validity test
if ($("#country2").is(':valid') || $("#country2").prop('validationMessage') == message) {
if ($('#country1').val() != $("#country2").val()) {
message = '';
}
$("#country2").setCustomValidity(message);
}
};
//test if country1 was changed
$("#country1")
.on('change', setCountryValidity)
;
//test if country2 was changed and ...
$("#country2")
.on('change', setCountryValidity)
//... on DOMready
.each(setCountryValidity)
;