我有一个表单,其中一个字段是到目前为止的文本值。我想避免值0但仍然允许输入分数,如1/3。然后重新计算我的分数并四舍五入到第四位。
因此我无法使用<input type="number" min="0.0001">
我该怎么做?
答案 0 :(得分:0)
为什么不对表单进行JavaScript验证?它可以让您更精确地了解您接受的数据类型。
示例JavaScript:
function validateNonzeroForm() {
var a = document.forms["myForm"]["nonzero_number"].value;
if (a == "0") {
alert("Nonzero field cannot be zero. Please enter a number.");
return false;
}
}
HTML:
<form name="demoForm" action="" onsubmit="return validateNonzeroForm()" method="post">
Please write numbers: <input type="number" name="nonzero_number">
<input type="submit" value="Submit">
</form>
答案 1 :(得分:0)
使用<form>
属性,根据您所需的<input>
要求验证所有.value
pattern
元素。
<强> JavaScript的:强>
function validateInputs(form){
var all_valid = true
for(var i=0; i<form.elements.length; i++ ){
var input = form.elements[i]
// Breakpoints:
// If we are not looking at an <input> element
// If the element does not have a pattern attribute
if( input.tagName.toLowerCase().indexOf('input') == -1 ) continue;
if( !input.getAttribute('pattern') ) continue;
// input Regex Pattern to test
var pattern = new RegExp(input.getAttribute('pattern'),'g');
if( pattern.test(input.value) ){
// Passed Test - Do Something
input.style.background = 'transparent'
}else{
// Failed Test - Do Something
input.style.background = '#FDD'
all_valid = false
}//endifelse
}//endfor
if(all_valid)
return true;
alert('That is not a valid entry')
return false
}//endfunction
<强> HTML:强>
<form onsubmit="return validateInputs(this);">
<input type="text" pattern="(^[^0]$)" />
<button>Go</button>
</form>
为了满足您的问题,
(^[^0]$)
的模式不允许任何模式 空白或零值。
如果您不想验证<input>
,请不要为其定义模式属性。
答案 2 :(得分:0)
<input>
中避免使用0值,允许输入分数,例如1/3,重新计算和舍入值到第4个小数。<强> JavaScript的:强>
function calculateFraction(form){
function returnError(){
alert("You must enter a 'non-zero' numeric value")
input.style.background = '#FDD'
return false
}
// Define input element to check
var input = form["fraction"] // Input MUST be type="text"
// Breakpoint - if value can't be evaluated.
if( !/^[0-9\/*\.\+-]*$/.test(input.value) )
return returnError();
// Evaluate statement. i.e. compute fractions, etc.
var value = eval(input.value)
// Test for '0'
if( Number(value)==0 ){
// Failed Test - Do Something
returnError()
return false
}
// Round to fourth decimal, define as the new input value
input.value = Math.round(value*10000)/10000
// Submit Form
return true
}//endfunction
<强> HTML 强>
<form onsubmit="return calculateFraction(this);">
<input type="text" name="fraction" />
<button>Go</button>
</form>
<强>注意事项强>
<input>
必须属于type="text"