I want to change my error message depending on how many digits the user enters in credit card field. I'm trying to generate the message variable with this:
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
}
creditCardMessage = numberDigit + 'Please enter between 13 and 16';
Then I want to pass the creditCardMessage variable in the following function:
function creditCardNumberEvent () {
if (!isCreditCardValid()) {
showErrorMessage ($cardNumber, creditCardMessage, $cardNumber, 'creditCardError');
} else {
removeErrorMessage($cardNumber, '#creditCardError');
}
}
All I get is the first value - the "too few digits." Thanks in advance.
When running your script, you can call CardNumberValid() which returns a Boolean, meaning you can use it in an if statement, like if(CardNumberValid())
function CardNumberValid() {
var valid = true;
var CardNumber = $("#CardNumber");
if (CardNumber.val().length < 13) {
$("#ErrorMsg").text("Too few digits. Please enter between 13 and 16");
valid = false;
} else if (CardNumber.val().length > 16) {
$("#ErrorMsg").text("Too many digits. Please enter between 13 and 16");
valid = false;
}
if(valid){
$("#ErrorMsg").text("");
}
return valid;
}
$('#Validate').click(function() {
alert("The card number " + (CardNumberValid() ? "is" : "is not") + " valid.");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="CardNumber" />
<div id="ErrorMsg" style="color:red;"></div>
<button id="Validate" type="button">Validate</button>
I think this is what you're trying to achieve:
function logValidationMessage() {
var cardNumber = document.getElementById('cardNumber');
var numberDigits = null;
if (cardNumber.value.length < 13) {
numberDigits = 'Too few digits. ';
} else if (cardNumber.value.length > 16) {
numberDigits = 'Too many digits. ';
} else {
numberDigits = 'Card number is valid.';
}
console.log(numberDigits);
}
document.getElementById('btnCheckCardNumber').addEventListener('click', logValidationMessage);
<input type="text" id="cardNumber" />
<input type="button" id="btnCheckCardNumber" value="Check" />
I did figure this out. I created a function as suggested and passed that function as an argument in another function: (which I now know is a callback function)
function creditCardMessageFunction () {
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
} else {
numberDigit = 'Numeric Values Only. ';
}
creditCardMessage = numberDigit + 'Please enter numbers between 13 and 16.';
return creditCardMessage;
}
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 have to do the password by this condition for creating password to follow this characteristics :
Contain at least 12 alphanumeric characters.
Contain both upper and lower case letters.
Contain at least one number (for example, 0-9).
Contain at least one special character (for example,!$%^&*()_+|~-=`{}[]:";'<>?,/).
i did this :
<input type="password" required pattern="^(?=.*[a-zA-Z])(?=.*\d)(?=.*
[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*{}()_=+]{12,}$"
name="password"
nblur="this.setCustomValidity(this.validity.patternMismatch
? 'Password must contain at least 12 characters, including upper
lowercase numbers and least special character' : '');
if(this.checkValidity()) form.password1.pattern = this.value;">
but when i try to put a password and confirm it always return not valid password
Sorry for this question, but with regExpression i put for this characteritics. Thanks in advance.
Write a series of test in JavaScript and control the submit event for your form.
var testPassword = (function() {
var allTests = [];
var minimumAlphaNumericCharacters = 12;
function countAlphanumeric(password) {
var count = password.length - password.replace(/[a-z]|\d/ig, '').length;
if (count < minimumAlphaNumericCharacters) {
return "Too few Alphanumeric Characters! At least " + minimumAlphaNumericCharacters + " nedded, " + count + " found";
}
return true;
}
allTests.push(countAlphanumeric);
function containsUpperAndLowerCharacters(password) {
var test = (password === password.toLowerCase());
if (test) {
return "Must contain both upper and lower case characters";
}
return true;
}
allTests.push(containsUpperAndLowerCharacters);
var minimumDigits = 1;
function containsMinimumDigits(password) {
var test = password.replace(/\D/ig, '').length;
if (test < minimumDigits) {
return "Must contain at least " + minimumDigits + " digits, " + test + " digits found";
}
return true;
}
allTests.push(containsMinimumDigits);
var minimumSpecials = 1;
function containsMinimumSpecials(password) {
var test = password.replace(/\w/ig, '').length;
if (test < minimumSpecials) {
return "Must contain at least " + minimumSpecials + " special symbols, " + test + " special symbols found";
}
return true;
}
allTests.push(containsMinimumSpecials);
return function testPassword(password) {
return allTests
.map(function(test) {
return test(password);
})
.filter(function(test) {
return test !== true;
});
};
})();
//TEST
var form = document.body.appendChild(document.createElement("form"));
var input = form.appendChild(document.createElement("input"));
var output = document.body.appendChild(document.createElement("pre"));
input.onchange = input.onkeyup = form.onsubmit = function(evt) {
var password = input.value.toString();
var test = testPassword(password);
output.textContent = test.join("\n");
if (evt.type == "submit") {
alert((test.length < 1 ? "Good" : "Bad") + " Password");
}
return false;
};
I have this javascript function:
if (myform.telephone.value.length < 10){
jAlert ('Please enter at least 10 characters!',function(){$(myform.telephone).focus();});
return false;
If the user enters less than 10 characters, an alert is triggered. I need to modify the script so that the alert pops if the user enters less than 10 DIGITS (0,1,2,etc)..
How can i do this ?
Update: As the OP correctly pointed out, there was a bug in the previous method. I advise not to use isNan as it is broken. I've updated the answer, code below.
This can be easily done by mathcing the input against a regular expression and then checking if the resulting number has 10 or more digits. Like:
var validate = function(){
var number = tryParseNumber(input.value);
if(number.toString().length < 10){
alert("Invalid input");
} else {
alert("Valid output: " + number);
}
};
var tryParseNumber = function (value) {
if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
return Number(value);
return false;
}
See this Fiddle for a working example.
Try :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
function phonenumber(inputtxt)
{
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following cod
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
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
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>