1 回答

TA貢獻1830條經驗 獲得超3個贊
你有required
并且你有一個pattern="^\d*(\.\d{0,2})?$"
您的貨幣代碼破壞了模式并停止提交,因為 HTML5 驗證在修改后的值上失敗
所以
允許貨幣模式或
顯示另一個字段,例如輸入的跨度或
像我在下面那樣刪除模式
如果用戶未能輸入有效金額,您可以在貨幣代碼中設置自定義錯誤
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP'
// format inital value
onBlur({
target: currencyInput
})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber(s) {
return Number(String(s).replace(/[^0-9.-]+/g, ""))
}
function onFocus(e) {
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e) {
const tgt = e.target;
var value = tgt.value
if (isNaN(value))
tgt.setCustomValidity('Please enter a valid amount');
else
tgt.setCustomValidity('');
var options = {
maximumFractionDigits: 2,
currency: currency,
style: "currency",
currencyDisplay: "symbol"
}
e.target.value = value ?
localStringToNumber(value).toLocaleString(undefined, options) :
''
}
<form action="{% url 'create_goal' %}" method="post">
<h4 class="mb-3" id="create">Create a Savings Goal</h4>
<input type="text" class="form-control" id="goalName" name="goalName" value="" required>
<input type="currency" min="0" class="form-control" id="goal" name="goal" required>
<button type="submit" class="btn btn-secondary btn-block">Add Goal</button>
</form>
添加回答
舉報