I need the validInput function to check if all input entered are numberic character/
The issue is when the first if statement return true, the function seems to skip the input check.
For example, if I enter 1 for input1, then "a" for input2, -3 for input3, the function will return true and shows the result.
https://codepen.io/regnagleppod/pen/NdWLYx
html:
<label>Starting Number: </label>
<input id="input1" type="text">
<br>
<label>Ending Number: </label>
<input id="input2" type="text">
<br>
<label>Step: </label>
<input id="input3" type="text">
<button onclick="return playButton()" id="play">Display Evens</button>
js:
function playButton(){
run();
if (validInput()){
showResult();
}
};
function validInput(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var z = document.getElementById("input3").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
Mohit are correct,
Change the function as follows,
function validInput(){
var x = document.getElementById("startingNum").value;
var y = document.getElementById("endingNum").value;
var z = document.getElementById("step").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
I have modified your code,please modified code
function playButton(){
run();
if (validInput()){
showResult();
}
};
function validInput(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var z = document.getElementById("input3").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
your mistake is very trivial you are comparing <=0 and isNaN with the value of x, i.e input1.(value) , Change the 2nd and 3rd if (condition) it will work.
Here is the changed code
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
Related
So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.
I am making a little 'guess the number' game, and I need to find a way to repeat the function based on what it outputs. What I have right now is this:
var input = prompt("Please enter a number between 1 and 100!");
var ranNum = Math.floor(Math.random()*100);
function numCheck()
{
if (input < 1)
alert("Please enter a valid number!");
else if (input > 100)
alert("Please enter a valid number!");
else if (input > ranNum)
alert("Try a little lower!");
else if (input = typeof stringValue)
alert("That is not a number!");
else if (input < ranNum)
alert("Try a little higher!");
else
alert("You got it!");
}
numCheck();
I did this using the inspect option on chrome on the page about:blank. Now that I have the function, I think I need to use another if else statement. It would detect if numCheck() output is You got it!" and if it didn't, it would replay the numCheck function, all the way until the player got the correct number.
How would I do it like that? And if there is a simpler way, what is it?
I made a fiddle that will use alerts and prompt accessible inside the page (I am not sure this what you asked for or not - explain more if not):
HTML:
<div class="numberguess">
<input type="text" id="entry" value="" />
<input type="button" id="send" class="" value="submit" />
</div>
<div id="alert"></div>
JS:
var _alert = document.getElementById('alert');
var ranNum = Math.floor(Math.random()*100);
function numCheck(){
var input = document.getElementById('entry').value;
if (input < 1 && input > 100)
_alert.innerText = "Please enter a valid number!";
else if (input > ranNum)
_alert.innerText = "Try a little lower!";
else if (typeof input != 'string')
_alert.innerText = "That is not a number!";
else if (input < ranNum)
_alert.innerText = "Try a little higher!";
else
_alert.innerText = "You got it!";
}
numCheck();
var el = document.getElementById('send');
el.addEventListener('click', function(){
numCheck();
}, false);
Check this as live exp: Jsfiddle
you can use looping like this code below
var input; // var to hold user input
var ranNum = Math.floor(Math.random()*100);
var win = false; // var if we want to ask another input
var trycount = 0; // don't want to ask for input forever
function numCheck()
{
if (input*1 != input) // check if number first
alert("That is not a number!");
else if (input < 1) // check lower bound
alert("Please enter a valid number!");
else if (input > 100) // check upper bound
alert("Please enter a valid number!");
else if (input > ranNum) // tell a hint
alert("Try a little lower!");
else if (input < ranNum) // tell a hint
alert("Try a little higher!");
else{
alert("You got it!");
win = true; // end the user prompt
}
}
while (!win && trycount < 3){ // while wrong guesses and below 3 tries
input = prompt("Please enter a number between 1 and 100! (" + ranNum + ")");
trycount++; // count the try
numCheck();
}
You need a looping mechanism that will keep prompting the user to input another value.
var ranNum = Math.floor(Math.random()*100);
function numCheck()
{
var input = prompt("Please enter a number between 1 and 100!");
if (input === null)
return false; // user pressed "cancel"
if (input == ranNum) {
alert("You got it!");
return false;
}
if (input < 1)
alert("Please enter a valid number!");
else if (input > 100)
alert("Please enter a valid number!");
else if (input > ranNum)
alert("Try a little lower!");
else if (input < ranNum)
alert("Try a little higher!");
else
alert("That is not a number!");
return true; // continue looping
}
while(numCheck());
I have this reg ex for alphanumeric validation that I got from this post
but it is not working with this function (I have a similar function for email and it works)
function checkName(field) {
var x = document.getElementById(field).value;
var y = /^[a-z0-9]+$/i;
//var z = /^[0-9]*$/;
if (x == "" || !x.match(y) ) {
alert("Invalid character");
if (x.length <= 2 || x.length >= 15) {
alert("Insert a name between 3 and 15 characters");
}
return false;
}
}
If I write some string/name I get both alerts. Can someone tell me what is wrong with this function?
Below is the approach for alphanumeric validation:
function checkName(field)
{
var x = document.getElementById(field).value;
if (x.length <= 2 || x.length >= 15)
{
alert("Insert a name between 3 and 15 characters");
return false;
}
var y = /^[0-9a-zA-Z]+$/;
if (x == "" || !x.match(y) )
{
alert("Invalid character");
return false;
}
alert("ALL OK");
return true;
}
<input type="text" id="textName" />
<button onClick="checkName('textName');">Check</button>
The Regex check for capital and small alphabets and numbers, and also checks for the length.
Your code works for me
function checkName(field) {
console.log(field);
var x = field;
var y = /^[a-z0-9]+$/i;
if (x == "" || !x.match(y) ) {
console.log("Invalid character");
}
if (x.length <= 2 || x.length >= 15) {
console.log("Insert a name between 3 and 15 characters");
}
}
//valid
checkName('testdskfjskdlf');
//invalid
checkName('slkjf*%');
//too long
checkName('jjjjjjjjjjjjjjjjjjjjjjjjjjj');
var ratioChange = prompt('Are you sure to change seller ration of this user?');
if(ratioChange != "")
{
$('#clsdywusers_hdnaction').val("SET_SELLER_RATIO");
$('#clsdywusers_seller_ratio').val(ratioChange);
}
else
{
alert('Please enter seller ratio.');
return false;
}
Now here what I want is that I only want to allow users to write digits in prompt box.Please help.
Use javascript input keypress event and check for every typed character if it's a number or not:
function is_numeric(val){
if(val > 47 && val < 58) return true;
else return false;
}
$(".your_input").keypress(function(e){
switch(e.which){
// exclude left and right navigation arrows from check
case 0: case 8:break;
default:
if(is_numeric(parseInt(e.which))) return true;
else{
return false;
}
}
});
Update: with prompt
var ratioChange = prompt('Are you sure to change seller ration of this user?');
if(ratioChange != "" && is_number(ratioChange))
{
$('#clsdywusers_hdnaction').val("SET_SELLER_RATIO");
$('#clsdywusers_seller_ratio').val(ratioChange);
}
else
{
alert('Please enter seller ratio.');
return false;
}
function is_numeric(val){
if(val > 47 && val < 58) return true;
else return false;
}
function is_number(val){
var value= new String(val), singleNumber;
for(var i=0; i < value.length; i++){
singleNumber = 48 + parseInt(value[i]);
if(!is_numeric(singleNumber)) return false;
}
return true;
}
JSBIN
I want to validate cell number using JavaScript.
Here is my code.
if(number.value == "") {
window.alert("Error: Cell number must not be null.");
number.focus();
return false;
}
if(number.length != 10) {
window.alert("Phone number must be 10 digits.");
number.focus();
return false;
}
Here is the issue, when I submit the form with out entering the phone number, it is showing the error cell number must not be null. it works fine.
When I submit the form with cell number less than 10 digits, it is showing phone number must be 10 digits. It is also fine.
The problem is when I submit the form with 10 digits, then also it is showing the error phone number must be 10 digits.
Please help me.
Thank You.
And also need the validation code for only digits for cell number.
If number is your form element, then its length will be undefined since elements don't have length. You want
if (number.value.length != 10) { ... }
An easier way to do all the validation at once, though, would be with a regex:
var val = number.value
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be ten digits")
number.focus()
return false
}
\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.
function IsMobileNumber(txtMobId) {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMobile = document.getElementById(txtMobId);
if (mob.test(txtMobile.value) == false) {
alert("Please enter valid mobile number.");
txtMobile.focus();
return false;
}
return true;
}
Calling Validation Mobile Number Function HTML Code -
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Please enter only Numbers.");
return false;
}
return true;
}
function ValidateNo() {
var phoneNo = document.getElementById('txtPhoneNo');
if (phoneNo.value == "" || phoneNo.value == null) {
alert("Please enter your Mobile No.");
return false;
}
if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {
alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");
return false;
}
alert("Success ");
return true;
}
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />
<input type="button" value="Submit" onclick="ValidateNo();">
If you type:
if { number.value.length!= 10}...
It will sure work because the value is the quantity which will be driven from the object.
This function check the special chars on key press and eliminates the value if it is not a number
function mobilevalid(id) {
var feild = document.getElementById(id);
if (isNaN(feild.value) == false) {
if (feild.value.length == 1) {
if (feild.value < 7) {
feild.value = "";
}
} else if (feild.value.length > 10) {
feild.value = feild.value.substr(0, feild.value.length - 1);
}
if (feild.value.charAt(0) < 7) {
feild.value = "";
}
} else {
feild.value = "";
}
}
Verify this code :
It works on change of phone number field in ms crm 2016 form .
function validatePhoneNumber() {
var mob = Xrm.Page.getAttribute("gen_phone").getValue();
var length = mob.length;
if (length < 10 || length > 10) {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
if (mob > 31 && (mob < 48 || mob > 57)) {} else {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
}
<script type="text/javascript">
function MobileNoValidation()
{
var phno=/^\d{10}$/
if(textMobileNo.value=="")
{
alert("Mobile No Should Not Be Empty");
}
else if(!textMobileNo.value.match(phno))
{
alert("Mobile no must be ten digit");
}
else
{
alert("valid Mobile No");
}
}
</script>
I used the follow code.
var mobileNumber=parseInt(no)
if(!mobileNumber || mobileNumber.toString().length!=10){
Alert("Please provide 10 Digit numeric value")
}
If the mobile number is not a number, it will give NaN value.
<script>
function validate() {
var phone=document.getElementById("phone").value;
if(isNaN(phone))
{
alert("please enter digits only");
}
else if(phone.length!=10)
{
alert("invalid mobile number");
}
else
{
confirm("hello your mobile number is" +" "+phone);
}
</script>