isnan function accepting dots - javascript

isnan() function also accepting .(dots). How to prevent them. This is sample code:
var Price = $("#Price").val();
if (Price == "") {
alert ("Required!");
}
else if (isNaN(Price)) {
$("#Price").val(Price);
alert("Enter digits");
}
I'm calling this JS code in KeyUp event of the Textbox.

else if (!/^\d+$/.test(Price)) {
// only digits
}

You can check the value is number by
function isNumber(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};

Try this one :
else if(price.match(/^[0-9]+$/)){
//Valid number
}

I found the solution:
var Price = "10.00";
if (Price == "") {
alert ("Required!");
}
else if(Price.search(".") != -1)
{
alert(" cannot insert dots!");
}
else if (isNaN(Price)) {
alert("Enter digits");
}
Here:http://jsfiddle.net/K8FUW/

Related

I have a javascript that checks if my form is valid and it stops checking after a certain field

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.

Jquery: check if variable is defined after keyup() function

Am creating register form with jquery function keyup(),
for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:
<script type="text/javascript">
$("document").ready(function() {
$("#txtuname").keyup(function() {
if ($("#txtuname").val().length < 6) {
jQuery("label[for='txtuname']").text("user name is too short");
}
if ($("#txtuname").val().length >= 6) {
var txtuname = $("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function() {
if (typeof txtuname == 'defined') {
alert("defined");
}
if (typeof txtuname == 'undefined') {
alert("undefined");
}
});
});
</script>
Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.
$("document").ready(function(){
var txtuname = null;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if( txtuname == null || txtuname.length < 6) ){
alert("incorrect");
}
else{
alert("correct");
}
});
});
Updated check of variable using comment of #Rhumborl , thx
Replace code with below condition -
if( typeof txtuname !== 'undefined' && txtuname.length >= 6) ){
//proceed further
}else{
alert('Please correct entries.');
return false;
}
I would put the validation logic in a function and call that, you can update this with your specific requirements and only do it once:
function isValidName(field) {
var myName = field.val().trim();
// some of this is redundant but just to show possibilities
var isValid = myName.length && myName.length >= 6 && myName && undefined !== myName && myName != " ";
var myLabel = $("label[for='" + field.attr('id') + "']");
if (isValid) {
myLabel.text("");
} else {
myLabel.text("user name is too short");
}
return isValid;
}
$("document").ready(function() {
$("#txtuname").keyup(function() {
isValidName($(this));
});
$("#submitRegistration").click(function() {
var nameIsValid = isValidName($("#txtuname"));
if (nameIsValid) {
alert("valid");
} else {
alert("undefined or invalid");
}
});
});
You are using $ as well as jQuery window.jQuery object in your code. Do not use both at time , you can check by both
jQuery("document").ready(function() { jQuery("#txtuname").keyup(function(){ if(jQuery("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if(jQuery("#txtuname").val().length>=6){
var txtuname=jQuery("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
jQuery("#submitRegistration").click(function(){
if(typeof txtuname =='defined'){
alert("defined");
}
if(typeof txtuname =='undefined'){
alert("undefined");
}
});
});
Or use by replace jQuery by $ sign. It will work.
you can try this way too......
$("document").ready(function(){
var txtuname;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if(typeof txtuname=="undefined"){
alert("undefined");
}
else{
alert("defined");
}
});
});

I want to stop non-alphabetical characters been put into the input

Currently I have a piece of javascript that stops the form been submitted if the inputs are empty but I want to make the script also stop non-alphabetical characters been put in too.
Here is the script
`function checkFormWhole(){
//var theForm = document.getElementById(id);
var letters = /^[A-Za-z]+$/;
var letnums = /^[A-Za-z0-9]+$/;
var theForm = document.getElementById("bookingForm");
if (theForm.customerType.value == ""){
alert("Please choose a customer type");
return false;
}
else if (theForm.customerType.value == "nonCorp" && theForm.forename.value == "") {
alert("Please Enter A Forename");
return false;
}
else if (theForm.customerType.value == "nonCorp" && theForm.surname.value == "") {
alert("Please Enter A Surname");
return false;
}
else if (checked == 0) {
alert("Please Choose An Event To Book");
return false;
}
else if (theForm.customerType.value == "corp" && theForm.companyName.value == "") {
alert("Please Enter A Company Name");
return false;
}
where i want the validation --->
else if (theForm.customerType.value == "nonCorp" && theForm.forename.value != (letters) /*|| theForm.customerType.surname.value.match != (letters)*/) {
alert("Please Enter A Forename Containing ONLY letters");
return false;
}
}`
You need to use the pattern as below.
var str = '123456';
var str2 = 'abcdEFG';
var patt = /[^a-zA-Z]/g;
// Contains non alphabet chars
if(patt.test(str) === true) {
console.log('Your input includes invalid characters')
}
// Contains alphabet chars only
if(patt.test(str2) === false) {
console.log('Your input includes valid characters')
}
You can simplify this but the example above has enough for you to be able to add the functionality you need.
Add your example to jsfiddle and if you have any problems, people can help you easier.

JavaScript regular expression 5-5000

I know that this:
var regStartMoney = /[1-5][0-9][0-9][0-9]/;
allows you to enter from 1-5999.
how do I do it for a range of 5-5000?
Regex misuse! Just do it the sane way:
var int = parseInt(input,10);
if (isNan(input)) {
alert('Please enter a number.');
} else if (input != int) {
alert('Decimals are not allowed.');
} else if (!(int >= 5 && int <= 5000)) {
alert('Your number must be between 5 and 5000 (inclusive).');
} else {
alert('Your number is valid!');
}
var regStartMoney = /^0*(?:[5-9]|[1-9][0-9][0-9]?|[1-4][0-9][0-9][0-9]|5000)$/;
Why not just:
var money = parseInt(input);
var test = Math.min(Math.max(money, 5), 5000);
if(money !== test) //
You should really convert to a number and compare. But that wasn't your question so here's your answer:
var regStartMoney = /^0*([5-9]|([1-9]\d{0,2})|([1-4]\d{3})|(50{3}))$/;
Here's a test script:
<script>
function checkMoney() {
var money=document.getElementById("money").value;
if (money.match(/^0*([5-9]|([1-9]\d{0,2})|([1-4]\d{3})|(50{3}))$/)) {
alert(money+" is between 5-5000");
} else {
alert(money+" is not between 5-5000");
}
}
</script>
<input id="money"/></br>
<input type="submit" onClick="checkMoney();"/><br/>
Test on jsfiddle

javascript cell number validation

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>

Categories