I have been trying form validation in javascript and html. I am stuck with the use of onblur(). The idea is that the user enters his name. If he moves out of the input area (textbox) without entering anything, then error message should be shown.
But according to my code below even if I enter anything, it still shows alert no name entered.
<form>
<input type="text" id="fn" value="First Name" onfocus="fnm()" onblur="chfnm()"/>
</form>
function fnm()
{
document.getElementById("fn").value=""; //clears default value of textbox
}
function chfnm()
{
var f=document.getElementById("fn");
for(var i=0;i<f.length;i++)
{
if(i!=(f.length-1))
fname= fname +f.elements[i].value +"<br>";
else
fname= fname+ f.elements[i].value;
}
if(fname=="") //error is fname is always an empty string
{
alert("Please fill your first name");
document.getElementById("fn").focus();
}
}
I am new to javascript so any new ideas are appreciated and welcome.
If you want to do validate that user inputting the name or not, you can simply use this code. If so you are putting extra code with for loop.
function fnm(){
document.getElementById("fn").value=""; //clears default value of textbox
}
var fname = "";
function chfnm(){
fname = document.getElementById("fn").value;
if(fname==""){
alert("Please fill your first name");
document.getElementById("fn").focus();
}else{
alert("your name " + fname);
}
}
DEMO
Just add required tag of html5 so no need to add extra java script function for checking
Related
I am writing three functions in javascript to do different things. Search functions only needs firstname and lastname. Add and update functions needs everything to filled out completely. I have those working, however when submitting form, if anything is missing, it alerts me but still submits it. I don't want it to do that, how can i do it?
function search() {
checkme = false
//alert('all feilds must be filled out');
var nameExpression = /^[a-zA-Z]+$/;
firstName = document.getElementById('firstName').value;
lastName = document.getElementById('lastName').value;
//check firstname
if (firstName!=""&&nameExpression.test(firstName)) {
checkme = true;
}else{
document.getElementById("firstName").classList.add("is-invalid");
alert("Please enter valid first name");
}
//check lastName
if (lastName!=""&&nameExpression.test(lastName)) {
checkme = true;
}else{
document.getElementById("lastName").classList.add("is-invalid");
alert("Please enter valid last name");
}
return checkme;
}
, here is how i am calling the function as well
<input name="Action" type="submit" name="Search" value="Search" onclick="return search();"">
The reason your function fails to stop submission, is because of a system called event bubbling, where an event propagates up the DOM tree, and any handlers related to that event are triggered. There are also default events that occur on certain actions. Some of these are cancelable events, one of which is the Form Submit event. The e.preventDefault() command basically cancels the default action of the event, which is submitting the form, and prevents it from submitting regardless of the output of your function. We then call the submit() function manually when all requirements are satisfied.
Here's a version that I feel is shorter and easier to understand. No checkme variables needed either. It assumes your form has the id yourForm, and submits it if both first and last names pass the RegEx check.
function search(e) {
e.preventDefault();
const nameExpression = /^[a-zA-Z]+$/;
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;
const yourForm = document.getElementById('yourForm');
if (nameExpression.test(firstName) && nameExpression.test(lastName)) {
yourForm.submit();
} else {
alert('All fields must be filled out, and contain only alphabets');
}
}
document.getElementById('yourForm').addEventListener('submit', search);
<form id="yourForm">
<input type="text" id="firstName" placeholder="First Name" />
<br>
<input type="text" id="lastName" placeholder="Last Name" />
<br>
<input name="Action" type="submit" name="Search" value="Search">
</form>
P.S. You can do what you are trying to do here in pure HTML by adding the pattern attribute to your first and last name inputs. This also helps in case the user has an extension like NoScript installed, but the downside is you cannot control how the validation error looks.
(I'm beginner/intermediate in JS) I once also worked on something like this. I would suggest to add a paramater of 'e' in your function, en then writing "e.preventDefault" In your code. It would prevent the default submit action of your form. And then, you can submit the form in JS if it matches a certain condition, and if not, it will give you an alert.
Im guessing checkme, firstName and lastName weren't defined yet.
function search(e) {
e.preventDefault();
var checkme = false;
//alert('all fields must be filled out');
var nameExpression = /^[a-zA-Z]+$/;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
//check firstname
if (firstName!=""&&nameExpression.test(firstName)) {
checkme = true;
} else {
document.getElementById("firstName").classList.add("is-invalid");
alert("Please enter valid first name");
}
//check lastName
if (lastName!=""&&nameExpression.test(lastName)) {
checkme = true;
} else {
document.getElementById("lastName").classList.add("is-invalid");
alert("Please enter valid last name");
}
if (checkme == true) {
your_form.submit();
}
This may not be a perfect solution to your problem, but this is roughly how I do these things with JS and validating forms. I hope this helped.
Edit:
The code is the author's source code, I tried to not edit it too much.
Really basic, I'm just trying to understand how to test a form using simple JavaScript without jQuery etc. Tried W3Schools but didn't work.
So I'm trying just a simple form instead with one field to get how it all works. Below I put a single field in a form, and thought I could test the fname variable against the firstName field.
But what happens is that the alert is never hit in the if statement. How to test the field firstName?
Any tips would be helpful.
function validateForm() {
var fname = document.getElementById("firstName");
if (fname == "") {
alert("first name is a mandatory field");
} else {
document.getElementById("formMessage").innerHTML = fname + " entered.";
}
}
<h2>Question 1 validate with alert popups</h2>
<p>Please enter the following mandatory information</p>
<form name="identification">
<p>First Name:<input type="text" id="firstName" /></p>
<p>
<button type="button" onclick="validateForm()">Submit</button>
</p>
</form>
<p id="formMessage"></p>
You're comparing the element itself. You should instead check the value of the element.
e.g.
var fname = document.getElementById("firstName").value;
fname is the element when you do document.getElementById, so you have to do:
function validateForm() {
var fname = document.getElementById("firstName");
if (fname.value == "") {
alert("first name is a mandatory field");
} else {
document.getElementById("formMessage").innerHTML = fname.value + " entered.";
}
}
You might also want to trim fname.value in case the user inputs bunch of empty spaces.
Use document.getElementById("firstName").value to get the value. if you don't add .value it means it didn't read the specified value.
I don't do much with Javascript.
What I'm looking to do is have a form where users can enter their zip code to see if they are within a select number of zip codes (the client's service area).
If their zip code is in the list, I want to send them to a URL for scheduling an appointment. If it isn't in the list, I want some sort of alert that says "Sorry, your zip code isn't in our service area".
I've got something adapted that kind of works, but sends the user to the page regardless of what they enter.
Any help is greatly appreciated!
<form name = "myform" action="http://www.google.com/">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5" onchange = "checkZip()">
<button id="submit">Submit</button>
</form>
<script type = "text/javascript">
function checkZip() {
var z = document.myform.zip;
var zv = z.value;
if (!/^\d{5}$/.test(zv)) {
alert("Please enter a valid Zip Code");
document.myform.zip.value = "";
myfield = z; // note myfield must be a global variable
setTimeout('myfield.focus(); myfield.select();', 10); // to fix bug in
// Firefox
return false;
}
var codes = [ 12345, 12346, 12347, 12348, 12349, 12350 ]; // add as many
// zip codes as
// you like,
// separated by
// commas (no
// comma at the
// end)
var found = false;
for ( var i = 0; i < codes.length; i++) {
if (zv == codes[i]) {
found = true;
break;
}
}
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
document.myform.zip.value = "";
return false;
} else {
alert("Press okay to go forward to schedule an appointment");
}
}
</script>
Non-submit Button (simple) Solution
<form name = "myform" action="http://www.google.com/">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
<button type="button" onclick="checkZip();" id="submit">Submit</button>
</form>
Note: a button with type="button" is a push button and does not submit w3c
And change the last block of checkZip() to:
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
document.myform.zip.value = "";
//do nothing
} else {
alert("Press okay to go forward to schedule an appointment");
document.myform.submit();
}
The changes I made were the following:
Move the onclick attribute from the input element to the submit button
Change the submit button to have a type of 'button', which makes it a push button. Push buttons do not automatically submit the the current form.
Note: This will not stop the situation where pressing enter inside the input element submits the form. You will need an onSubmit="" handler according to the next solution to handle that use case.
Submit button (simple) solution
<form name = "myform" action="http://www.google.com/" onsubmit="checkZip()">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
<button onclick="checkZip();" id="submit">Submit</button>
</form>
Note: a button with no type is a submit button by default w3c
And change the last block of checkZip() to:
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
return false;
} else {
alert("Press okay to go forward to schedule an appointment");
return true;
}
The changes I made were the following:
Move the checkZip() call to the onsubmit attribute on the form
Change checkZip() to return true/false
On Change Solution
This solution most closely replicates yours. However it adds more complexity:
The Form:
<form name = "myform" action="http://www.google.com/" onsubmit="onFormSubmit();">
Enter Your Zip Code
<input type = "text" id="zipCode" name = "zip" size = "5" maxlength = "5" onchange = "onZipChange()">
<button id="submit">Submit</button>
<div id="invalidZipMsg" style="display:none;">
Sorry, but we do not service your area.
</div>
</form>
The JavaScript:
/**
* Returns true if we receive a valid zip code.
* False otherwise.
*
* #param zipCode The zip code to check
* #returns True/fase if valid/invalid
*/
function isValidZip(zipCode){
var validZipCodes = {'12345':true,
'12346':true,
'12347':true,
'12348':true,
'12349':true,
'12350':true
};
//can do other checks here if you wish
if(zipCode in validZipCodes){
return true;
} else {
return false;
};
}
/**
* Run on invalid zip code.
* Disables form submission button and shows
* error message.
*/
function invalidZipCode(){
var invalidZipMsg = document.getElementById('invalidZipMsg');
invalidZipMsg.style.display = "block";
var submitButton = document.getElementById('submit');
submitButton.disabled = 'true';
}
/**
* Run on valid zip code. Enables form
* submission button and hides the error message.
* #returns
*/
function validZipCode(){
var invalidZipMsg = document.getElementById('invalidZipMsg');
invalidZipMsg.style.display = "none";
var submitButton = document.getElementById('submit');
submitButton.disabled = 'true';
}
/**
* onChange handlers for the zip code input element.
* Will validate the input value and then disable/enable
* the submit button as well as show an error message.
* #returns
*/
function onZipChange(){
var zipCode = document.getElementById('zipCode');
if(isValidZipCode(zipCode.value)){
validZipCode();
} else{
invalidZipCode();
};
}
/**
* Run on form submission. Further behavior is the same
* as #see onZipChange. Will stop form submission on invalid
* zip code.
*/
function onFormSubmit(){
var zipCode = document.getElementById('zipCode');
if(isValidZipCode(zipCode.value)){
validZipCode();
return true;
} else{
invalidZipCode();
return false;
};
}
Notes
There are many ways to solve this problem. I just chose the two easiest ones and one that I feel offers a better user experience. The non-submit solution is a good example for when you have buttons that don't submit, but provide other actions that don't require a form submission. The last one has the best user experience in my opinion, but that is just an opinion.
Off Topic
If you have time I would suggest you check out many of the fine JavaScript libraries that are available. They help introduce complex/advanced issues with simple solutions that make sense and are more than likely cross-browser compliant. I suggest them in my order of my preference:
jQuery w/ jQuery UI
Prototype w/ Scriptaculous
Dojo
Be aware though, that they will take time to understand. I know that when working on a project that is not the top priority.
The fastest way to get started with jQuery and JavaScript in general is here: First Flight. I am not associated w/ codeschool.com in anyway nor do I get any profits from them. This example is free and it is the one that my team passes around at work for people just starting off with jQuery.
I'm assuming your problem is that the user can still submit the form even though the zipcode is invalid.
I'd recommend moving the check into the form submit event like this
<form name = "myform" action="http://www.google.com/" onsubmit = "checkZip()">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
<button id="submit">Submit</button>
</form>
Then you can just return false when the check fails to cancel the submission to google.com
My validation function looks like that.
var fname = $("#fname").val();
var lname = $("#lname").val();
function validate() {
var isValid = true;
if (!fname) {
$("#fname").attr('class', 'invalid');
isValid=false;
}
if (!lname) {
$("#lname").attr('class', 'invalid');
isValid=false;
}
It simply changes the class of unfilled input box.
I know that i can write else for every if and change back to default (class="valid") if user fills some of inputs. But how can i create something universal for all inputs to change back to default class the input that user has filled after first validation error?
That was good Tural! HOWEVER, why the excess processing in your code? That will add unecessary stress. Since you, for what you "solved", will add the "valid" class to ALL the input type text or password, just add that to the actual input element in the straight code:
<input class='valid' ..... />
Now, back to your original validation: why not make it universal?:
function validate(formField) {
if !formField $('#'+formField).removeClass('valid').addClass('invalid');
}
Or something in that vein ...
You can either assume everything is valid and then try to disprove that or you can try to prove its validity. The below takes the first approach and sets all the classes to "valid" to be consistent with that.
function validate() {
// Get the current form input state.
var fname = $("#fname");
var lname = $("#lname");
// Assume everything valid until proven otherwise.
var isValid = true;
fname.attr('class', 'valid');
lname.attr('class', 'valid');
if (!fname.val()) {
fname.attr('class', 'invalid');
isValid=false;
}
if (!lname.val()) {
lname.attr('class', 'invalid');
isValid=false;
}
return isValid;
}
Ok. I found the way
$('input[type="text"],input[type="password"]').keypress(function () {
$(this).attr('class', 'valid');
});
Currently I am trying to setup my contact form to give an error message when an invalid email is entered. When a blank or incorrect e-mail is submitted the page should do the following:
Sign Up text changes to 'Retry'
Red text appears within input field stating 'Address entered not valid'
When the user focuses on the input field, or presses 'retry'; all the form elements should go back to their original state. I have been able to get the text to change from red to black using the onFocus method. I attempted to create a small little javascript named reset, which I hoped to change the DIV text from 'Retry' back to 'Sign Up'.
I'm certain my issue is with the Javascript. Can someone point me in the right direction? :)
For code reference:
http://itsmontoya.com/work/playdeadcult/indextest.php
One way of doing this is, with the html:
<form action="" method="post">
<fieldset>
<label for="emailAddress">Sign up for the newsletter</label>
<input type="text" id="emailAddress" name="email" />
<button id="submitButton" type="submit">Submit</button>
</fieldset>
</form>
And the JavaScript:
var emailEntry = document.getElementById('emailAddress');
var button = document.getElementById('submitButton');
var defaultButtonText = button.innerHTML;
emailEntry.onblur = function(){
var val = this.value;
// the following IS NOT a valid test of email address validity
// it's for demo purposes ONLY
if (val.length < 5 && val.indexOf('#') == -1){
button.innerHTML = 'retry';
button.style.color = 'red';
}
else {
button.innerHTML = defaultButtonText;
button.style.color = 'black';
}
};
button.onclick = function(){
// prevent submission of the form if the email was found invalid
// and the innerHTML was therefore set to 'retry'
if (this.innerHTML == 'retry'){
return false;
}
};
JS Fiddle demo.
Try this instead:
function validate() {
if($("#buttonDiv").html()== 'Retry')
{
// oops! They are trying to get back to where they were by
// re-clicking retry. Let's reset this thing
reset()
return false;
}
var emDiv = document.getElementById('email') // only look up once.
if(emDiv) {
// the space after the . should allow for 6 long
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/;
var address = emDiv.value;
// good form issue -- never use == false. use !
if(!reg.test(address)) {
emDiv.value = 'Address entered not valid';
emDiv.style.color = '#bf4343';
emDiv.style.fontSize = '12px';
$("#buttonDiv").html( 'Retry' );
return false;
}
}
}
Is it just the commented out block of your reset() function what you need help with? If so, you can try the jQuery version of it since you have jQuery loaded anyway =)
The following is for your reset() function which changes text color to red:
$('#email').val('').css('color', '#FF0000').css('font-size', '18px');
The following is for your blur() function which changes text color to black. Attach this to your email input text box as well and you should be set:
$('#email').blur().css('color', '#000000');