Reputation: 455
I have an html form and want to create a Javascript code that would check if the Tel. field include only numbers. It is an exercise so I don't want to use jQuery or any other library. I put together this:
HTML
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" onsubmit="return numberedFieldsCheck()">
<table>
<tr>
<td>
<label for="tel">Telephone</label></td>
<td>
<input type="text" placeholder="00441293603275" name="tel" id="tel" />
<span id="telFieldIntCheck" style="display:none;color:red">You can only use numbers.</span>
</td>
<td>
<input type="submit" name="button" id="button" value="Submit" />
</td>
</tr>
</table></form>
JS
function numberedFieldsCheck(){
var x=document.getElementById('tel').value;// retrieving value from the form
console.log(x);
if(!integerCheck(x)){
alert('wrong format');
document.getElementById('telFieldIntCheck').style.display="inline";
return false;
}
}
function integerCheck(userInput) {
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
if (typeof userInputArr[i]=="number")
{console.log('format ok')}
else {return false};
}
}
Can you help me with the code? It alerts wrong format regardless of what I put into the input field. Console logs appear for a millisecond and disappear straight away.
Upvotes: 0
Views: 140
Reputation: 1944
Since you only need to check if the field contains only numbers, this should work :
function numberedFieldsCheck(){
var x=document.getElementById('tel').value;
// Checks if the field is empty.
if(x.trim() == '') {
alert("Tel field can't be empty.");
return false;
}
if(!integerCheck(x)){
alert('Wrong format !');
document.getElementById('telFieldIntCheck').style.display="inline";
return false;
}
alert("Alright !");
// Note that this return true is important. You weren't
// returning anything even in the case where everything was fine.
// If you don't, it will return 'undefined' by default, which is
// casted to 'false' in checks. So that means the function returns
// false even if everything is alright.
return true;
}
function integerCheck(userInput) {
// Now, all the elements of usrInputArr will contain strings only.
// That means typeof <element> will always return "string".
var userInputArr=userInput.split('');
for (i=0;i<userInputArr.length;i++){
char = userInputArr[i];
// Comparing by ASCIIs should work just fine.
if (! (char >= '0' && char <= '9' || char == ' ') )
return false;
}
return true;
}
You should also do what @hindmost said in the comments of your question i.e. changing the forms onsubmit
to return numberFieldCheck()
.
Upvotes: 1