我想知道我可以使用哪种类型输入电话号码。
当我这样做时,我可以输入字母:
<input type="tel" id="phone" name="phone" required>
另外,我想删除右边的那个箭头:
<input type="number" id="phone" name="phone" required>
使用tel您可以添加一些验证以仅允许数字(您也可以+预先添加并包含您需要的任何国家/地区代码)。
<form>
<input type="tel" id="phone" name="phone" pattern="[+]{1}[0-9]{11,14}" required>
<button>Submit</button>
</form>
这会在您提交时出现错误
或者您可以限制为数字并通过执行以下操作隐藏箭头:
.no-arrow {
-moz-appearance: textfield;
}
.no-arrow::-webkit-inner-spin-button {
display: none;
}
.no-arrow::-webkit-outer-spin-button,
.no-arrow::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
<form>
<input id="phone" name="phone" class="no-arrow" value="" type="number">
<button>Submit</button>
</form>
以上所有解决方案都没有避免用户在输入中添加非数字,例如,当您在<input />标签上设置模式属性时,用户可以输入非数字char,但是当用户提交表单时出现浏览器错误
如果你想限制你的输入只是数量,你必须这样做js
纯JS
const inputValidation = (e) => {
// get value form event
const value = e.target.value
// validate value
const validatedValue = value.replace(/[^0-9]/g, '');
return validatedValue;
}
反应 JS
// Implement your input state
const [mobile, setMobile] = React.useState("");
// validate value
const numberHandler = val => {
const validatedValue = val.replace(/[^0-9]/g, "");
setMobile(validatedValue);
};
你的输入标签
return (
<div>
<input type="tel" value={mobile} onChange={e => numberHandler(e)} />
</div>
)
此外,如果用户输入无效数据,您可以向用户显示警报
const numberHandler = val => {
const validatedValue = val.replace(/[^0-9]/g, "");
+ // implement alert
+ if (validatedValue === "" && val !== "") {
+ alert('you must enter number only')
+ return
+ }
setMobile(validatedValue);
};
如果只是通过删除箭头解决了您的问题,那么您可以尝试包含 css 来禁用它:
#phone::-webkit-inner-spin-button,
#phone::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
我建议使用这个 js 库来格式化输入字段: