Specific number validation? - javascript

Is it possible to validate a field to a specific set of numbers using javascript? Say for example in a postcode field you can only enter four numbers to be be accepted e.g. 2747,2750, 2753, 2760, 2777. Any other number will be returned as false. I have done a bit of searching around but i can't seem to find anything of use for this specific situation and i'm quite knew to javascript so any sort of help would be great.

Should be really simple:
Live DEMO
Create a list of your numbers
Create an Object with every number as a key and whatever as a property.
If they come from the server, send and parse them as JSON.// skip
In JS, var validNumbers = JSON.parse(serverResponse); // skip
Use an Object, not an Array. Array.prototype.indexOf is slower and needs polyfill.
Object property access is O(1) and universally supported.
Your object looks like this: var validNumbers = {"2747": "2747", etc..}
Get the input from the user.
if (typeof validNumbers[userInput] !== undefined) {//valid} else {//invalid}

try this.
<html>
<head>
<script>
function validateForm() {
var x = document.getElementById("entry_834285895").value;
if ((x != 3242 )&&(x != 2342 )&&(x != 2343 )&&(x != 1111 )) {
document.getElementById("um").innerHTML = ('Invalid');
document.getElementById("um").style.color = 'Red';
}
else {
document.getElementById("um").innerHTML = ('Valid');
document.getElementById("um").style.color = 'Green';
}
}
</script>
</head>
<body>
<p>Valid numbers:<br> 3242<br>2342<br>2343<br>1111
<form name="myForm" action="" target="hiddenFrame"
onsubmit="return validateForm()" method="post" >
Name: <input id="entry_834285895" type="text" name="fname">
<input type="submit" value="Submit">
<div id="um"></div>
</form>
<iframe name="hiddenFrame" style="display:none;"></iframe>
</body>
</html>

Related

The input from client side should entered only digits, if is alphabets should give an error msg

Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {

Is there a way to pass two arguments to a JavaScript function through HTML?

I am trying to create an .html page that will allow for two string inputs (arguments) to be passed to the parameters of a .js function that will then return the longer of the 2 input values by comparing the string lengths.
First I wrote a .js that actually works while running it through VS CODE. Here it is:
function twoStrings(stringA, stringB) {
let longerStr;
if (stringA.length > stringB.length) {
return longerStr = stringA;
} else return longerStr = stringB;
}
console.log(twoStrings("three", "Baseball"))
Then I tried to create an .html file that will create the user interface. But I think there is an issue that at the end of each input line it is calling the function.
<!DOCTYPE html>
<head>
<title>Return Longest String.html</title>
</head>
<body>
<p>Please input two words:</p>
<input type="string" id="myInput1" oninput="twoStrings()">
<input type="string" id="myInput2" oninput="twoStrings()">
<p id="longerStr"> is the longer word</p>
<script type="text/javascript" src="twoStringsV1.js"></script>
</body>
</html>
and here is my .js
// 3. Write a function that takes in two strings and returns the longer of the two
function twoStrings(fval, sval) {
var fval = document.getElementById("myInput1").value;
var sval = document.getElementById("myInput2").value;
let longerStr;
if (fval.length > sval.length) {
return longerStr = fval;
} else return longerStr = sval;
}
document.getElementById("longerStr").innerHTML = longerStr;
One other thing is that at the end of my .html, where I am asking the .js to produce an innerHTML I am getting this line:
[object HTMLParagraphElement]
Thank you for your assistance.
Get rid of the return statements, and put the assignment to innerHTML inside the function.
The function doesn't need any parameters, it gets the values of the two inputs itself.
function twoStrings() {
var fval = document.getElementById("myInput1").value;
var sval = document.getElementById("myInput2").value;
let longerStr;
if (fval.length > sval.length) {
longerStr = fval;
} else {
longerStr = sval;
}
document.getElementById("longerStr").innerHTML = longerStr;
}
<p>Please input two words:</p>
<input type="string" id="myInput1" oninput="twoStrings()">
<input type="string" id="myInput2" oninput="twoStrings()">
<p id="longerStr"> is the longer word</p>
The reason you were getting [object HTMLParagraphElement] is because outside the function, the global variable longerStr refers to the element <p id="longerStr">; converting an object to a string produces a result like that.
There are some opportunities to use some more native elements:
<input type="string" is not valid. type="text" is a valid type but is also the default and can be omitted.
<output> would be a good fit for the computed result of a form calculation
It would be simpler to handle the input event at a higher level (the overall form) rather than twice for each input and have the function bound to explicit inputs internally.
You can also rely on the fact that elements specified with id=x are globally available on window as x to simply your inline handlers.
function longerStr(stringA, stringB) {
return stringA.length > stringB.length
? stringA
: stringB;
}
<!DOCTYPE html>
<html>
<head>
<title>Return Longest String.html</title>
</head>
<body>
<p>Please input two words:</p>
<form oninput="longerStrOut.value=longerStr(myInput1.value, myInput2.value)">
<input id="myInput1">
<input id="myInput2">
<p>
<output name="longerStrOut"></output>
is the longer word
</p>
</form>
</body>
</html>

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>

I have issues with my JavaScript

I don't what happen with my script can i please point out where is my mistake. 1 to 9 all condition working fine but when you put 10-12 is not work
<form method="post" enctype="multipart/form-data" action="#">
<input type="hidden" value="2" id="itemstock" name="itemstock">
<input value="1" name="quantity" id="quantity" class="text">
<button type="submit" onClick="return checkoption();" >Click </button>
</form>
Javascript
function checkoption()
{
var itemqty = document.getElementById('quantity');
var iss = document.getElementById('itemstock');
if(itemqty.value > iss.value)
{
alert('We have Currently '+iss.value+' In Stock');
}
else
{
alert('add to cart');
}
}
Thank you in advance
Screen short see qty i put 13 but its not showing error
Using the < or > operators with strings will compare the values alphabetically, which is probably not what you want.
You need to compare these as numbers, not as strings. JavaScript allows you to easily cast a string to a number using +, like so:
var qty = +itemqty.value;
var isv = +iss.value;
if(qty > isv)
{
// ...
}
However, you can also use parseInt (which will return NaN if the value is invalid) if you want to add more error checking in your code.
The .value attribute on a text field such as input is a string, not a number. Therefore, you compare strings lexicographically. Change them into numbers, either via parseInt(str, 10) or via +str.

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources