简体   繁体   English

将电话号码输入字段限制为仅接受6个8位和10位数字

[英]Restrict a phone number input field to accept only 6 8 and 10 digit numbers

I have a phone number input field that looks like this: 我有一个电话号码输入字段,如下所示:

<input type="text" name="phone" maxlength="10" size="40" value="{$tmp.phone}"><>

Can I apply a code inside here? 我可以在这里应用代码吗? Or would I apply a function in an external .php file to do this? 还是我会在外部.php文件中应用函数来执行此操作?

What would the code look like? 代码是什么样的?

I am new to all this coding stuff and need some help... 我对所有这些编码东西都是陌生的,需要一些帮助...

You can use the new HTML5 attribute pattern . 您可以使用新的HTML5属性pattern New browsers will not send the form until it is filled correct: 在正确填写表格之前,新的浏览器将不会发送该表格:

<form>
<input type="text" name="phone" pattern="^[0-9]{6}|[0-9]{8}|[0-9]{10}$" />
<input type="submit" />
</form>

If a user is using an older browser, the attribute is ignored. 如果用户使用的是较旧的浏览器,则将忽略该属性。 In this case you still should check it as Daniel and Pheonix recommended. 在这种情况下,您仍然应该按照Daniel和Pheonix的建议进行检查。

Even if get some way to put a check in HTML, always do validation on your server side. 即使可以通过某种方式在HTML中进行检查,也请始终在服务器端进行验证。 Client side Validations can always be by-passed. 客户端验证始终可以被绕过。

in server side 在服务器端

$phone = $_GET['phone'];

if(!(strlen($phone)==6 ||strlen($phone)==8 ||strlen($phone)==10)){
  //Error
}

For better user experience you can validate using javascript, and for security reasons is mandatory to use server side validation as Pheonix said. 为了获得更好的用户体验,您可以使用javascript进行验证,并且出于安全原因,如Pheonix所说,必须使用服务器端验证。

<form id="form_id">
<input id="phone_id" type="text" />
<input type="submit" 
    onclick="if (document.getElementById('phone_id').value.length != 6 
                 && document.getElementById('phone_id').value.length!=8 
                 && document.getElementById('phone_id').value.length!=10) 
                 { 
                     alert('Error message...'); 
                     return false; 
                 }" />
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM