How can i validate form with JavaScript - 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>

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)) {

Form is being submitted in IE11

The below form is being submitted even when its txt_approver is empty.
But it works well in firefox/chrome?
I get no error, what could be the issue?
<script>
function validateForm() {
var x = document.forms["warningnotice"]["txt_approver"].value;
alert(x);
if (x == null || x == "") {
alert("Please enter a name to send a email to ");
return false;
}
}
</script>
<form method="post" action="travel.cfm" id="commentForm" name="warningnotice" onsubmit=" return validateForm()">
<td ><input type="text" name="txt_approver" class="get_empl" required data-error="#errNm35"></td>
<input type="submit" name="Submit" value="Submit" >
</form>
You are using the name attribute to locate the form and the textbox in JavaScript. This is not what the name attribute is for. The id attribute is for this.
Instead of:
document.forms["warningnotice"]
and
<input type="text" name="txt_approver" ...
Those lines should be:
document.forms["commentForm"]
and
<input type="text" name="txt_approver" id="txt_approver"...
And, instead of document.forms, use:
var form = document.getElementById("commentForm");
var tb = document.getElementById("txt_approver");
Also, instead of:
if (x == null || x == "")
You can just use:
if (!String.trim(x))
Because an empty textbox will produce an empty string "" and an empty string, converted to a boolean (which an if statement looks for) will be false, but a populated one, will convert to true.
Lastly, you probably don't want to have your submit button have a name attribute at all because when the form is submitted, the value of the submit button will be submitted along with the other form elements, which probably is not what you want.
The following JS Fiddle shows the code that is working for me in IE 11: https://jsfiddle.net/x0rbnL5s/

Can't get if/else function to work with radio buttons

I have looked all over this site (and Google) for an answer to my problem but I can only seem to find bits and pieces, nothing specific.
I am primarily playing around with JavaScript and HTML but am not trying to use jquery right now.
So, with that said, this is what I'm trying to do: I would like the user to enter two numbers, select an operation (add, subtract, multiply, divide) out of a list of four radio buttons, and then click a button which is linked to a function that does the math and then presents it in a text box on the page. How would I do this using only HTML and JavaScript? I have gotten everything to work up until the point I add the radio buttons.
The code is as follows:
<script>
function operationForm (form) {
var x = document.operationForm.getElementById("numberOne");
var y = document.operationForm.getElementById("numberTwo");
var operation;
var answer;
if (document.operationForm.addSelect.checked === true) {
answer = x + y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.subtractSelect.checked === true) {
answer = x - y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.multiplySelect.checked === true) {
answer = x * y;
document.operationForm.answerBox.value = answer;
} else(document.operationForm.divideSelect.checked === true) {
answer = x / y;
document.operationForm.answerBox.value = answer;
}
}
</script>
<h1>Let's calculate!</h1>
<form name="operationForm">
<p>
<label>Enter two numbers, select an operation, and then click the button below.
<p>
<label>Number One:
<input type="text" name='numbers' id="numberOne">
<br>
<br>Number Two:
<input type="text" name='numbers' id="numberTwo">
<p>
<input type="radio" name="operations" id="addSelect" value=''>Add
<input type="radio" name="operations" id="subtractSelect" value=''>Subtract
<input type="radio" name="operations" id="multiplySelect" value=''>Multiply
<input type="radio" name="operations" id="divideSelect" value=''>Divide
<label>
<p>
<input type="button" value=" Calculate " onClick='operationForm(form);'>
<p>
<label>Your answer is:
<input type="text" name="answerBox">
If anyone has any fixes or can point me in the right direction of the correct syntax for handling radio buttons, functions linking to them, and onClick events linking to those functions, it would be extremely appreciated.
Consider replacing the <input type="button" value=" Calculate " onClick='operationForm(form);'> with <input type="button" value=" Calculate " onClick='operationForm();'>. Next change the function operationForm to accept no parameters. Then add id to your input answer box. Next for each if statement in the function use the elementById function to get the radios and the answerBox. For example, the first if should be
if (document.getElementById("addSelect").checked) {
answer = x + y;
document.getElementById("answerBox").value = answer;
}
This works:
JavaScript:
<script type="text/javascript">
function operationForm(){
var form = document.forms['operation_form'];
var x = form['numberOne'].value*1;
var y = form['numberTwo'].value*1;
var operation = null;
var answer = null;
if (form['addSelect'].checked == true) {
answer = x + y;
} else if (form['subtractSelect'].checked == true) {
answer = x - y;
} else if (form['multiplySelect'].checked == true) {
answer = x * y;
} else if (form['divideSelect'].checked == true) {
answer = x / y;
}
form['answerBox'].value = answer;
}
</script>
HTML:
<form name="operation_form">
<label>Enter two numbers, select an operation, and then click the button below.</label>
<br/>
<label>Number One:</label><input type="number" name='numberOne' />
<br/>
<br/>Number Two:</label><input type="number" name='numberTwo' />
<br/>
<input type="radio" name="operations" id="addSelect" value='' />Add
<input type="radio" name="operations" id="subtractSelect" value='' />Subtract
<input type="radio" name="operations" id="multiplySelect" value='' />Multiply
<input type="radio" name="operations" id="divideSelect" value='' />Divide
<br/>
<input type="button" value=" Calculate " onclick="operationForm();" />
<br/>
<label>Your answer is:</label><input type="text" name="answerBox">
</form>
Fixes between this and your example:
There are a ton of things wrong with the code you provided. I will update this answer shortly with as many as I can remember.
Update:
Please remember this is meant to be helpful and not punishing. So keep in mind that while listening to the attached feedback, I want you to learn this stuff.
Notes on your HTML:
1.) The biggest problem is none of the <label> elements have closing</label> tags.
Although, none of your html elements have any closing tags.
This will group all of the elements inside one big parent <label>.
So when the browser auto-closes the unclosed tags at the end of the document, this causes a hodgepodge of mixed up child elements. Close your elements.
2.) The first two text boxes have the same name="numbers" attribute. You can only do that with radio type inputs.
3.) Your <form> name="" attribute can NOT have the same name as the JavaScript function you are trying to call. They are stored in the same browser namespace so it causes an error.
Notes on your JavaScript:
1.) Your checked === true is an exact comparison. This will almost never evaluate to be truthful. Use checked == true, or better yet, just use if( my_element.checked ){}. Sometimes .checked will equal a string like this: .checked = 'checked'. So even though 'checked'==true it will never be truthful for 'checked'===true. The === means Exactly Equal. So only true===true.
2.) Your var x = document.opera.. ... .mberOne"); will store the whole <input> element into the x variable. You need to have ...mberOne").value; so just the value of the <input> is stored, not the whole html element.
3.) The only object that has a getElementById() method is the document. You can't use that from a document form object.
4.) You have to convert your x any y input values to numbers. If not, 5 + 5 will give you 55 instead of 10 because they are treated as strings. I multiplied them by * 1 to do that. I also changed the <input type='text' attribute to type='number' just to be safe.
5.) You can assign your answerBox.value just one time at the end of the function instead of doing it once per if(){} bracket. It will work the same but it's just much more readable.
6.) I used the syntax of form['numberOne'] instead of form.numberOne but they both work the same. It is referencing the element name (not necessarily the id) as it exists inside the form. <form> is the only object that lets you do this, whereas a <div> or <p> does not.

JavaScript Prevent text entry if it does not meet parameters

When working with a JavaScript function I want to prevent characters from being entered into a form if they do not meet certain parameters. The original JavaScript code I used was:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
That function worked while I was using only 1 input point in my form, however when I tried to use that function over multiple inputs it would only affect the first one in the form.
When creating a function that could be reused by multiple input boxes I got the following code:
function validateLetter(dataEntry){
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
}
catch(InputError) {
window.alert(InputError)
return false;
}
return true;
}
The form I am using to input information is:
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the city you were born in:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter" name="letter" onkeypress="validateLetter()">
</p>
</form>
Does anyone know a way to translate the last line of the first function: document.getElementById("letter").value = replacedInput;
To something that can be re-used with the current code.
I tried:
dataEntry.value = replacedInput
But that did not seem to run/change the function at all
The problem is in textInput.replace() - you forgot the second parameter. So instead of textInput.replace(/[^A-Za-z]/g);, you need textInput.replace(/[^A-Za-z]/g, "");.
As noted in the MDN website:
The ID must be unique in a document, and is often used to retrieve the element using getElementById.
In your example above, you are using the same value for the ID attribute on all of the input fields. Also, the name attribute should be unique within forms. The answer provided here explains in greater depth. With that said, in the examples below I have modified your input fields in respect to the above.
First off, the initial function you provided was pretty close. One issue with it is that the replace() method would need a second parameter. This parameter can be a string or a function to be called for each match. In your case I believe you just want an empty string:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
Secondly, you can reference the current input field that is invoking validateLetter() by passing it along to the function as a parameter using the keyword this.
onkeypress="validateLetter(this);"
On a sidenote: You might achieve a better user experience using onkeyup instead of onkeypress. The example below utilizes this event instead so you can compare and judge for yourself.
Here is everything put together in a working example:
function validateLetter(target) {
var textInput = target.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
target.value = replacedInput;
}
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="maiden" name="maiden" onkeyup="validateLetter(this);" />
</p>
<p>Enter the city you were born in:
<input type="text" id="city" name="city" onkeyup="validateLetter(this);" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="street" name="street" onkeyup="validateLetter(this)">
</p>
</form>

How to remove attributes from HTML using javascript?

I have an HTML with say a textfield (input element).
<input name="capacity" type="text" value="blah blah blah">
This simply displays a text field on my page with a default value "blah blah blah".
What I want to do is remove value attribute, as I don't want to see this default value.
I am doing this using javascript.
value = element.getAttribute("value");
if((element.readOnly != undefined || element.readOnly == false) || (element.disabled != undefined || element.disabled == false)){
//element.removeAttribute(value);
element.removeAttribute("value");
But it is not working. I even tried
element.setAttribute("value","");
but no luck.
Any pointers where I may be missing.
EDIT :
I got an issue related to this question, anyone interested may check this
*********************************************
Thanks a lot.
...I don't want to see this default value.
Just set the value property directly to an empty string.
document.getElementsByName('capacity')[0].value = '';
jsFiddle.
Give your text field and id like <input name="capacity" type="text" id="text" value="blah blah blah"> document.getElementById['text'].value = "";
This is your html tag. You will need to add a ID to it
<input id="capacity" name="capacity" type="text" value="blah blah blah">
This is just to fire the javascript function
<input type="submit" value="Click" onclick="javascript:return reset();" />
The following function will reset the value of the selected element
<script type="text/javascript" language="javascript">
function reset() {
document.getElementById("capacity").value = "";
return false; // In order to avoid postback
}
</script>
If you are not using form and you want to use it with just the name you can try the following
this.capacity.value = '';

Categories

Resources