validating using input.value.match in javascript - javascript

I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.

It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.

You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}

Related

Struggling with making a little number guessing game

How can I make "You got it!" message to pop up when my input is not only 5, but lower or equal to 5?
document.getElementById("my-button").onclick = function() {
if (document.getElementById("my-input").value == "5") {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
You have to convert your value to a number using Number, and then compare it using <=.
document.getElementById("my-button").onclick = function() {
if (Number(document.getElementById("my-input").value) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
You need to convert the input value which is a string to number before comparing it.
In this case you can use parseInt
document.getElementById("my-button").onclick = function() {
if (parseInt(document.getElementById("my-input").value, 10) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>
The value that u get from input type is string so u need to convert it to number with [ ParseInt, Number ] methods after that u can compare and everytings will work fine so i think it's better of u
let button = document.getElementById("my-button");
let value = document.getElementById("my-input");
button.on('click', function () {
if (Number(value) <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
have a nice game
A slight issue with your question is that the type of the input is text rather than number. You can change the type of the input by doing <input type=number id="my-input">.
If you want to keep the type you will have to check if the input is a number.
In either case you will have to convert the value of the input from string to number since numeric operations using strings are wrong most of the time (there are rare specific cases where the outcome is the same). The only difference between using text and number is having to check if the value of the input is valid, which you can do using isNaN after the conversion. I usually prefer forcing JavaScript to convert the text by using - 0 over parseInt or parseFloat, since it's scricter and will not convert "123test" to 123.
Here is a solution working with number
document.getElementById("my-button").addEventListener("click", function() {
if (document.getElementById("my-input").value - 0 <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="number" id="my-input">
<button id="my-button">Submit</button>
Here is a solution working with text
document.getElementById("my-button").addEventListener("click", function() {
var value = document.getElementById("my-input").value - 0;
if (isNaN(value)) {
alert("Not a number");
} else if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
});
<input type="text" id="my-input">
<button id="my-button">Submit</button>
Actually when you access the value of <input> its a string. You can't use >,<,>=,<= between strings you use need to convert it into a number using parseInt()
document.getElementById("my-button").onclick = function() {
let value = parseInt(document.getElementById("my-input").value)
if (value <= 5) {
alert("You got it!")
} else {
alert("Opps, wrong number. Please try again.")
}
}
What is my favorite numbers?
<input type="text" id="my-input">
<button id="my-button">Submit</button>

regular expression in javascript user input

I am having a problem with regular expression in javascript. What i am trying to do is a form register in which i must validate the first name so i decided to go with javascript validation (can you please tell me if going with js is the better option or going with ajax php reg validation?). So I wrote my code by checking some tutorials and reading from google but i am still having a problem. It is not working ! It runs on blur event using jquery so I need your help please to do this.
The pattern i am trying to check is for special characters in the user input
/[\'^£$%&*()}{##~?><>,|=_+]+$/g;
here is my script:
$(document).on('blur','.first_name_input', function() {
var firstNameInput = $(".first_name_input").val();
if (firstNameInput !== '') {
//var exp = /[a-zA-Z0-9-]+$/g;
var exp = /[\'^£$%&*()}{##~?><>,|=_+]+$/g;
//if (firstNameInput.test(/^[\'^£$%&*()}{##~?><>,|=_+-]+$/)) {
//if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
if (firstNameInput.match(exp)) {
var firstnameValidity = "<div class='name_not_valid_div'>× Not allowed characters present!</div>";
$('body').prepend(firstnameValidity);
$(".name_not_valid_div").hide().fadeIn('slow');
if (!errorArray.includes("firstName")){
errorArray.push("firstName");
}
} else {
$(".name_not_valid_div").hide();
if (errorArray.includes("firstName")){
for(var i = errorArray.length - 1; i >= 0; i--) {
if(errorArray[i] === "firstName") {
errorArray.splice(i, 1);
}
}
}
}
}
});
and my html code is :
<tr>
<td class="label">First Name: </td>
<td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
</tr>
1st: use .trim() to avoid left/right whitespaces or even the spaces without any characters $(".first_name_input").val().trim();
2nd: for validation
// if the string has special characters
function string_has_spec_char(str){
var reg = /[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
var reg = /\s/g;
return reg.test(str);
}
and use it like
if(string_has_spec_char(firstNameInput) === false){
// the first name doesn't have special characters
}
if(string_has_spaces(firstNameInput) === false){
// the first name doesn't have spaces
}

Regex to allow only positive whole numbers and checking validity in jQuery

I have two input field like this in my HTML:
<input type="text" class="txtminFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Minimum Feedback">
<input type="text" class="txtmaxFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Maximum Feedback">
I've tried several regex patterns like following:
^\d+([\.\,][0]{2})?$
or
(^[0-9]+$|^$)
or
/^\d*$/
None of these worked whatsoever with the following code in jQuery:
if ($('.txtminFeedback').val() == "" && $('.txtmaxFeedback').val() == "") {
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
} else if (!$('.txtminFeedback')[0].checkValidity() || !$('.txtmaxFeedback')[0].checkValidity())
{
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
User can leave the txtminfeedback and txtmaxfeedback empty if he wants. However if he decides to enter some values, then both fields must be entered and will require to have entered only whole positive numbers (from 0 to 4 million).
What am I doing wrong here?
In the end this did it:
pattern="^(\s*|\d+)$"
if ($('.txtminFeedback')[0].checkValidity()==false || $('.txtmaxFeedback')[0].checkValidity()==false) {
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
Just in case someone in future might need it.
Cheers =)

Form validation woes

New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.

Limiting input field to one decimal point and two decimal places

I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?
This is my input field
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
Here is my validation script.
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var amount = parseFloat($(this).val());
if (amount) {
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Jonah
This should do :
var ok = /^\d*\.?\d{0,2}$/.test(input);
(if I correctly understood that you don't want more than 2 digits after the dot)
The code thus would be :
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Assuming that:
There MUST have 2 digits after a decimal point, and
There must be at least 2 digits before the decimal point, but no more than 3 digits
The code you would use to match it would be:
var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);
It would be much easier if you used the Masked Input Plugin for jQuery.

Categories