iPad 上的 Mobile Safari 应该是兼容 HTML5 的,但似乎 required 属性不起作用。有人知道为什么,或者有一个不需要大量 JavaScript 的不错的解决方法吗?
我的代码
<input type=email class=input placeholder="Email" name="email" required>
iOS 尚不支持:什么时候可以使用:必需。
这是该问题的 jQuery 解决方案,它也以粉红色突出显示失败的输入字段。
$('form').submit(function(){
var required = $('[required="true"]'); // change to [required] if not using true option as part of the attribute as it is not really needed.
var error = false;
for(var i = 0; i <= (required.length - 1);i++)
{
if(required[i].value == '') // tests that each required value does not equal blank, you could put in more stringent checks here if you wish.
{
required[i].style.backgroundColor = 'rgb(255,155,155)';
error = true; // if any inputs fail validation then the error variable will be set to true;
}
}
if(error) // if error is true;
{
return false; // stop the form from being submitted.
}
});
从 iOS 10.3 开始,支持该属性。
您可以在提交操作之前执行以下操作:
<form name="myForm" action="valid.html" onsubmit="checkValid()" method="post">
... ...
</form>
按下
submit
按钮后,在实际提交之前会触发 checkValid()
。返回值 true
将继续提交操作。
请参阅这篇文章以获取更多说明。
如果您已经在使用 jQuery、Modernizr 和 yepnope,这是处理它的一种方法。如果你不这样做,那么这会添加很多额外的 javascript。
如果你使用PHP,你可以添加这样的验证
function validation(){
if(isset($_POST['submit'])){
$email = $_POST['email'];
if(empty($email)){
echo $error = "Your email cannot be empty";
} else {
return true; //or do something next here
}
}
然后您可以在 php 中的表单之前添加此函数。