我有两个要求输入字段的表单之一:HTML5必要属性两个字段
<form>
<input type="tel" name="telephone" required />
<input type="tel" name="mobile" required />
<input type="submit" value="Submit" />
</form>
是否有可能得到浏览器来验证所以只需要其中的一个?即如果电话被填满,不要乱丢手机是空的,一个错误反之亦然
我有两个要求输入字段的表单之一:HTML5必要属性两个字段
<form>
<input type="tel" name="telephone" required />
<input type="tel" name="mobile" required />
<input type="submit" value="Submit" />
</form>
是否有可能得到浏览器来验证所以只需要其中的一个?即如果电话被填满,不要乱丢手机是空的,一个错误反之亦然
我有一些想法,发挥各地,现在有这个问题的一个有效的解决方案使用jQuery:
jQuery(function ($) {
var $inputs = $('input[name=telephone],input[name=mobile]');
$inputs.on('input', function() {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', !$(this).val().length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
Telephone:
<input type="tel" name="telephone" value="" required />
<br />Mobile:
<input type="tel" name="mobile" value="" required />
<br />
<input type="submit" value="Submit" />
</form>
它使用两个输入input
事件,当一个不为空它将另一个输入的必需属性设置为false。
我已经写了jQuery plugin包裹上述的JavaScript代码,以便它可以在元件的多个组使用。
对于我的需求进行了一些调整,此工作非常好,谢谢.. – Anupam
你会做的更好形式的数据验证的JavaScript无论如何,这是因为HTML5验证不会在旧的浏览器。这里是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation Phone Number</title>
</head>
<body>
<form name="myForm" action="data_handler.php">
<input type="tel" name="telephone">
<input type="tel" name="mobile">
<input type="button" value="Submit" onclick="validateAndSend()">
</form>
<script>
function validateAndSend() {
if (myForm.telephone.value == '' && myForm.mobile.value == '') {
alert('You have to enter at least one phone number.');
return false;
}
else {
myForm.submit();
}
}
</script>
</body>
</html>
。
现场演示这里:http://codepen.io/anon/pen/LCpue?editors=100。如果您愿意,请告诉我这是否适合您。
感谢您的回答。不过,所以我不打扰旧的浏览器表单验证是在服务器端完成。 HTML5表单验证是对具有较新浏览器的用户的渐进增强,我希望使用这些浏览器并显示浏览器的本机错误消息 – Andy
我认为这将是出HTML的控制,而且你将不得不实行某种形式的JS功能。快速谷歌显示了这个的jsfiddle http://jsfiddle.net/LEZ4r/1/所以你可以有一个if语句的控制。希望这有助于... – CheckeredMichael
看看[**这个**](http://stackoverflow.com/a/10694930/3509874)回答! – urbz