Recalling data user has input and showing if it is a number - javascript

This is a two part question, I currently have the below code and I'm trying to have it so that the console will tell me if it is a lower case letter or an upper case letter or of it is a number. I cant seem to get the number.isInteger to work so please tell me where I am going wrong with that.
Also I would like to have it so that there is a call back of what the user entered. So instead of it just saying "This is a upper case letter" I would like it to state "The letter g you entered is lowercase" and vice versa for upperCase and numbers.
Hope that makes sense, please find below my current code. I am new to coding and javascript so please try dumb it down as much as possible for me. Thanks!
Please see below code I currently have:
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if (upperLower == upperLower.toLowerCase()) {
console.log("The character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log("The character is uppercase");
}
else if (upperLower == Number.isInteger()){
console.log("This is a number");
}

Or you can check if input converted to number is not a number (isNaN) is false
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if (!isNaN(parseInt(upperLower))){
console.log(upperLower + " is a number");
}
else if (upperLower == upperLower.toLowerCase()) {
console.log(upperLower + " character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log(upperLower + " character is uppercase");
}

Related

Having problems with regex in Javascript

I am currently making a senior memory book my English class, and because I'm a nerd I am going to put a bit of code in it. Well, I'm having a bit of trouble with regex in my code.
My entire code:
//For future reference, "alert(*parametes*)" will make an alert box with the parameters inside it.
//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase()
//Creates the entered phrase backwards.
var phraseBackwards = ""
for (var x in phrase) {
phraseBackwards += phrase[(phrase.length - 1) - x]
}
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
alert("The phrase you entered was a palindrome.")
}
//This happens if the preavious condition was false.
else {
//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace("/\s+/g", '') == phrase) {
alert("The phrase you entered would have been a palindrome, had it not had spaces")
} else {
//Checks to see if the phrase you entered, even without spaces, is not a palindrome.
if (phraseBackwards.replace(/\s+/g, '') != phrase) {
alert("The phrase you ented was not a palindrome.")
}
}
}
The particular portion that is not functioning correctly:
//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace(/\s+/g, '') == phrase) {
alert("The phrase you entered would have been a palindrome, had it not had spaces")
}
I realize that some of my code may not be optimal but I'm trying to hurry and finish because I procrastinated until last minute.
So there are a few points to note in my edit.
First of all, you need to remove all non word characters from the initial phrase using this: replace(/\W/g, "")
Then reverse the string: phrase.split("").reverse().join("")
Then check if phraseBackwards == phrase.
Note: The code you used to used to reverse the string was valid. But given your use for this, I thought you might want to make it shorter.
//For future reference, "alert(*parameters*)" will make an alert box with the parameters inside it.
//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase().replace(/\W/g, "");
//Creates the entered phrase backwards.
var phraseBackwards = phrase.split("").reverse().join("");
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
alert("The phrase you entered was a palindrome.");
}
//This happens if the previous condition was false.
else {
alert("The phrase you ented was not a palindrome.");
}
phraseBackwards without spaces can't be == to the original phrase, because the original has spaces. Remove spaces from the original phrase as well. – Jeremy Thille

How to avoid to enter repeated number in input text form?

I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,
sample code,
var mobNumber = $('#phNo').val();
if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
alert('Please enter valid phone number');
}
You could use following regex ^(\d)\1+$ :
^ asserts position at start of the string
(...) 1st capturing group
\d matches a digit (equal to [0-9])
\1 matches the same text as most recently matched by the 1st capturing group
+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).
See following example:
function test(par){
if(par.match(/^(\d)\1+$/g)){
console.log(par + " is not valid");
}else{
console.log(par + " is valid");
}
}
test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");
I hope it helps you. Bye
You can simply write code like
$(document).on('input', '#phNo', function() {
var mobNumber = $(this).val();
var res = mobNumber/(mobNumber/10);
if(res == 111111111) {
alert('Please enter valid phone number');
}
});
this is applicable for all numbers and you have to check the max and min length of the input ..
You can try like this,
var phone = "11111111";
var phonecount = phone.length;
var countLength = 0;
for (var i in phone)
{
if(phone.substring(0,1)==phone[i])
{
countLength = countLength + 1;
}
}
if (countLength == phonecount)
alert("Please enter valid phone number");
try this :
var checkPhone = function() {
phone_number = $('#phone').val();
res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
if(res == '1'){
return 'bad phone number';
} else {
return 'good phone number';
}
}
Test it here : JSFIDDLE

Number validation in JavaScript

I have created an external JavaScript to validate a form I created in HTML. Some of the validation works, but when I use the same code to validate other fields it will not work. E.g. postcode must contain numbers - if not, postcode is invalid.
I tried using the same code for a credit card, i.e. credit card must have 16 digits - if not, the credit card number is invalid. I wrote the code for postcode and it worked, but when I tried to reaarrange it to suit the credit card function, it did not work. Not too sure why? Should I have used a different function?
Here is my external javascript:
function validateForm()
{
if (isNaN(document.getElementById("postcode").value))
{
alert ("Your postcode is not valid");
}
else
{
alert ("You have entered your postcode correctly");
}
if (document.getElementById ("email").value.length < 5 ||
document.getElementById ("email").value.indexOf("#")== -1)
{
alert("Please enter your email min 5 chars and include # symbol");
document.getElementById("email").focus();
return false;
}
if (isNaN(document.getElementById("creditcard").value))
{
alert ("Your creditcard is not valid");
}
else
{
alert ("You have entered your creditcard correctly");
}
alert("Thank you for your submission!");
return true;
}
So first off, you probably don't want to prompt the user with 10 error dialogs at a time.
So you should nest your if else clauses & the function will stop after the first error.
Second, isNaN is doubtfully a good evaluator because input.value may return a value of type string. Using a regex is a more robust way of error checking inputs. Third, you want to account for the user's confusion mistakes. Users often think (me too): 'wait, should I also write the dash on my credit card here?'.
So you'll remove dots, dashes & whitespace before proceeding (those could unknowingly be included). Other chars are just invalid. For your credit card input, that would be:
var ccVal = document.getElementById("creditcard").value;
// remove dots, dashes & whitespace
ccVal = ccVal.replace(/(\s|\.|\-)/g, '');
// if any other chars there, input value = incorrect & stop function
if ( ccVal.match(/\D/) ) {
alert('A credit card number only has decimals, silly.');
return false;
} else {
// Check for length now
if ( ccVal.length !== 16) {
alert('A credit card has 16 decimals, silly.');
return false;
} else {
// more checks
document.getElementById('myform').submit()
}
}
See an implementation example here: http://jsbin.com/betawahi/1/edit
isNaN checks if the value is not an integer, you'll need an additional check for the length.
Keeping the code similar to the way you've set out the rest of the function, to check if the credit card is a number and a length of 16, you'll want:
if( !(isNaN(document.getElementById("creditcard").value) && document.getElementById("creditcard").value.length === 16) {
alert("Credit Card Is Valid");
}else{
alert("Your Credit Card is Not Valid");
return false;
}

Check If only numeric values were entered in input. (jQuery)

I would like to check if users enter correct phone number in, with help of jQuery, so far I got to this stage:
var phone = $("input#phone").val();
if (phone !== "") {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
Basically it checks if phone number was entered and if it was, I would like to check if it is a numeric value and if it is not display the error messages.
Could anyone help with checking if it is numeric?
Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit
if(phone.match(/^\d+$/)) {
// your code here
}
There is a built-in function in jQuery to check this (isNumeric), so try the following:
var phone = $("input#phone").val();
if (phone !== "" && !$.isNumeric(phone)) {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
I used this to check if all the text boxes had numeric values:
if(!$.isNumeric($('input:text').val())) {
alert("All the text boxes must have numeric values!");
return false;
}
or for one:
$.isNumeric($("txtBox").val());
Available with jQuery 1.7.
http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.
If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
I hope this code may help you.
in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".
Thanks... :)
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.
Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.
<input oninput="formatPhone()">
function formatPhone(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}

Validating textbox entry through javascript

I wanted to allow only characters in a textbox and space in between two characters.I am trying to avoid any unwanted characters and blank string in following Javascript code.
var filter = "^[a-zA-Z''-'\s]{1,40}$";
var label = $('#<%= txtName.ClientID %>').val();
if ((label.length > 0) && (label!= '')) {
if (label.match(/^[a-zA-Z \s]{1,40}$/)) {
if (label.match(/^\s$/)) {
alert("Please Enter a Valid name");
return false;
}
else {
$("#myModal").dialog('open');
}
}
else {
alert("Please Enter a Valid name");
}
}
else {
alert("Please Enter a Valid name");
}
This is working fine for everything except when user enters more than 1 space in the textbox. I was thinking that label.match(/^\s$/)) will take care of blank string or blank spaces.
Thanks
It looks like this is a job for 0 or more (the RegEx *)! (Pardon the exclamation, I'm feeling epic this morning)
/^\s$/ means "contains only one space"
I believe you are looking for
/^\s*$/ means "contains only zero or more spaces"
you should use + sign in regular expression for more than one entities.suppose if you want multiple spaces then use like var expr=/(\s)+/

Categories

Resources