how do I check if a text entered is a number and has nine characters in javascript?
Intengo do with the code below but shows me correctly.
function numberValidate(idtelf){
var number = document.getElementById('idtelf');
var charactersLength = number.value.length;
if(isNaN(number) || charactersLength !=9 )
{
alert( "Enter a valid number ");
}
else {
alert( "correct");
}
};
This one checks also if it's a number. Other answers would accept "123456 " (3 spaces at the end) as well.
function numberValidate(idtelf){
var input = document.getElementById('idtelf');
var number = parseFloat(input.value);
var charactersLength = input.value.length;
var numberLength = (""+number).length;
if(isNaN(number) || charactersLength !=9 || numberLength !=9 )
{
alert( "Enter a valid number ");
}
else {
alert( "correct");
}
};
If number can'n be float then instead of parseFloat() use parseInt()
You can use
HTML
<input id="idtelf">
Javscript
var number1 = document.getElementById('idtelf');
number1.onblur = function () {
var charactersLength = number1.value.replace(/\s/gi,"").length;
if(isNaN(number1.value) || charactersLength != 9)
{
alert("Enter a valid number ...");
}
else {
alert("correct");
}
};
https://jsfiddle.net/rreyaovy/5/
Try this..This handles all type of input..
function numberValidate(idtelf){
var input = document.getElementById('idtelf');
var number = input.value.toString();
var myString = number.replace(/\D/g,'');
if(number.length ==9 && number.length == myString.length)
{
alert( "Correct");
}
else {
alert( "Enter a valid number");
}
};
Demo
Here's a function that uses a simple regular expression to test if the value is a 9-digit number.
function numberValidate(id){
var number = document.getElementById(id).value,
regex = /^[0-9]{9}$/;
if (regex.test(number)) {
return true;
} else {
return false;
}
};
We can use this function like this:
function numberValidate(id){
var number = document.getElementById(id).value,
regex = /^[0-9]{9}$/;
if (regex.test(number)) {
return true;
alert();
} else {
return false;
}
};
var result1 = numberValidate('testNum1');
var result2 = numberValidate('testNum2');
var result3 = numberValidate('testNum3');
document.getElementById('result').innerHTML = 'Input 1: ' + result1 + '<br/>Input 2: ' + result2 + '<br/>Input 3: ' + result3;
<input id="testNum1" value="1234">
<input id="testNum2" value="123456789">
<input id="testNum3" value="1234567891011">
<div id="result"></div>
try like this
if(isNaN(number.value) || charactersLength !=9 )
instead of this
if(isNaN(number) || charactersLength !=9 )
Related
Having trouble with a combined file of html, CSS and javascript that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html"
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = function() {validate()};
var cancel = document.getElementById("cancel");
cancel.onclick = function cancelBooking()
}
window.onload = init;
it's common rule of eslint, if you want to ignore these error on you code, you can use eslint-disable on top of your js code
/* eslint-disable */
alert('foo');
The problem is inside your init() function. I have corrected it please try using this. You were calling the function cancelBooking() like this function cancelBooking() which was giving error.
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = function() {validate()};
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking()
}
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 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
Creating a script to prompt alert if all number entered are zeros. Script is working correctly but through JS error in firebug console if number entered correctly.
How could i solve this without error prompt.
Code -
jQuery("#EventPhone").focusout(function(){
var $this = jQuery(this);
var phoneNum = ($this.val()).toString();
var count1 = phoneNum.match(/0/g).length || "";
var phoneNumLen = phoneNum.length
if( phoneNumLen == count1 )
{
alert('All numbers in a phone number cannot be zero!!');
$this.val("");
}
});
Fiddle - http://jsfiddle.net/8XmpG/
UPDATE (if characters are allowed)
use this code - DEMO
jQuery("#EventPhone").focusout(function(){
var phoneNum = parseInt($(this).val().trim().replace( /\D+/g,''));
if(phoneNum === 0 )
alert("All numbers in a phone number cannot be zero!");
});
if characters are not allowed, use this code- DEMO
jQuery("#EventPhone").focusout(function(){
var $this = jQuery(this);
var phoneNum = $this.val().trim();
var phoneNumber = parseInt(phoneNum);
if(phoneNum == phoneNumber && phoneNumber !== 0 ) // don't use phoneNum === phoneNumber
{
alert("Right Number");
}
else{
alert('Wrong Number');
$this.val("");
}
});
Now, you have error in this line:
var count1 = phoneNum.match(/0/g).length || "";
because phoneNum.match(/0/g) could be null, so, if you check it first like this:
var count1 = (phoneNum.match(/0/g) && phoneNum.match(/0/g).length) || "";
everything will be ok.
Check for space:
var phoneNum = ($this.val()).toString().replace(' ', '');
I am trying to get it so that if I type in a name that ends with a space, the textfield will go red. Most of the code works its just one method does not seem to be working.
The issue must be somewhere in the last index part?
var NamePass = true;
function ValidateName() {
var BlankPass = true;
var GreaterThan6Pass = true;
var FirstBlankPass = true;
var BlankMiddleName = true;
if (document.getElementById('Name').value == "") {
BlankPass = false;
}
var Size = document.getElementById('Name').value.length;
console.log("Size = " + Size);
if (Size < 7) {
GreaterThan6Pass = false;
}
if (document.getElementById('Name').value.substring(0, 1) == " ") {
FirstBlankPass = false;
}
var LastIndex = document.getElementById('Name').value.lastIndexOf();
if (document.getElementById('Name').value.substring((LastIndex - 1), 1) == " ") {
FirstBlankPass = false;
}
string = document.getElementById('Name').value;
chars = string.split(' ');
if (chars.length > 1) {} else
BlankMiddleName = false;
if (BlankPass == false || GreaterThan6Pass == false || FirstBlankPass == false || BlankMiddleName == false) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
http://jsfiddle.net/UTtxA/10/
lastIndexOf gets the last index of a character, not the last index in a string. I think you meant to use length instead:
var lastIndex = document.getElementById('Name').value.length;
Another problem with that, though, is that substring takes a start and end index, not a start index and a substring length. You could use substr instead, but charAt is easier:
if (document.getElementById('Name').value.charAt(lastIndex - 1) == " ") {
FirstBlankPass = false;
}
Now, for some general code improvement. Instead of starting with all your variables at true and conditionally setting them to false, just set them to the condition:
var NamePass = true;
function ValidateName() {
var value = document.getElementById('Name').value;
var BlankPass = value == "";
var GreaterThan6Pass = value.length > 6;
var FirstBlankPass = value.charAt(0) == " ";
var LastBlankPass = value.charAt(value.length - 1) == " ";
var BlankMiddleName = value.split(" ").length <= 1;
if (BlankPass || GreaterThan6Pass || FirstBlankPass || LastBlankPass || BlankMiddleName) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
A couple more points of note:
It’s probably a good idea to use camelCase variable names instead of PascalCase ones, the latter usually being reserved for constructors
blah == false should really be written as !blah
An empty if followed by an else can also be replaced with if (!someCondition)
That function looks like it should return true or false, not set the global variable NamePass
Penultimately, you can sum this all up in one regular expression, but if you intend to provide more specific error messages to the user based on what’s actually wrong, then I wouldn’t do that.
function validateName() {
return /^(?=.{6})(\S+(\s|$)){2,}$/.test(document.getElementById('name').value);
}
And finally — please keep in mind that not everyone has a middle name, or even a name longer than 6 characters, as #poke points out.