JavaScript 阻止表单提交

我正在处理一个 Django 项目,其中一个表单不会提交。我发现罪魁祸首是一些格式化货币输入的 JavaScript(当我删除 JS 或删除输入type="currency"时,它会提交)

这是我的简化形式 - JS 来自用于货币/货币的 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) {

  var value = e.target.value


  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" pattern="^\d*(\.\d{0,2})?$" class="form-control" id="goal" name="goal" required>


  <button type="submit" class="btn btn-secondary btn-block">Add Goal</button>


</form>


慕斯709654
浏览 119回答 1
1回答

牛魔王的故事

你有required并且你有一个pattern="^\d*(\.\d{0,2})?$"您的货币代码破坏了模式并停止提交,因为 HTML5 验证在修改后的值上失败所以允许货币模式或显示另一个字段,例如输入的跨度或像我在下面那样删除模式如果用户未能输入有效金额,您可以在货币代码中设置自定义错误如何创建 html5 自定义验证?var currencyInput = document.querySelector('input[type="currency"]')var currency = 'GBP'// format inital valueonBlur({&nbsp; target: currencyInput})// bind event listenerscurrencyInput.addEventListener('focus', onFocus)currencyInput.addEventListener('blur', onBlur)function localStringToNumber(s) {&nbsp; return Number(String(s).replace(/[^0-9.-]+/g, ""))}function onFocus(e) {&nbsp; var value = e.target.value;&nbsp; e.target.value = value ? localStringToNumber(value) : ''}function onBlur(e) {&nbsp; const tgt = e.target;&nbsp; var value = tgt.value&nbsp; if (isNaN(value))&nbsp; &nbsp; tgt.setCustomValidity('Please enter a valid amount');&nbsp; else&nbsp; &nbsp; tgt.setCustomValidity('');&nbsp; var options = {&nbsp; &nbsp; maximumFractionDigits: 2,&nbsp; &nbsp; currency: currency,&nbsp; &nbsp; style: "currency",&nbsp; &nbsp; currencyDisplay: "symbol"&nbsp; }&nbsp; e.target.value = value ?&nbsp; &nbsp; localStringToNumber(value).toLocaleString(undefined, options) :&nbsp; &nbsp; ''}<form action="{% url 'create_goal' %}" method="post">&nbsp; <h4 class="mb-3" id="create">Create a Savings Goal</h4>&nbsp; <input type="text" class="form-control" id="goalName" name="goalName" value="" required>&nbsp; <input type="currency" min="0" class="form-control" id="goal" name="goal" required>&nbsp; <button type="submit" class="btn btn-secondary btn-block">Add Goal</button></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript