form detects inputs in real time - javascript

guys I'm new here and it's my first time posting . been learning html / CSS / javascript since 5 months ago and now I'm trying to build a very simple contact form where if there's no value it will show error icon + message error blow the input , been trying to figure it out for like 12h+ but nothing i saw in stack worked ....... already have the solution of a guy , he used javascript to manipulate the style and add and remove the error using css , but i want to do it the other way around with manipulating the DOM with JAVA using document.query Selector
let firstname = document.querySelector("#inputfirst").value;
let form = document.querySelector('#loginform')
//form.addEventListener('submit', (e) => {
// e.preventDefault();})
function validation() {
if (firstname == "" || firstname == null || firstname == " ") {
document.querySelector("#inputfirst").classList.add("firstname")
document.querySelector("#firstname_Error").innerHTML = "firstname"
return false;
}
else {
document.querySelector("#inputfirst").classList.remove("firstname")
document.querySelector("#firstname_Error").innerHTML = ""
}
}
/**testing for 1st input only **/
.firstname {
background-image: url(./images/icon-error.svg);
background-position: 24rem 13px;
background-repeat: no-repeat;
border: 1px solid rgb(247, 10, 10);
}
<form novalidate id="loginform" name="loginform" onsubmit="return validation()"; >
<input id="inputfirst" name="firstname" type="text" placeholder="First Name" class="button-shap" required >
<span id="firstname_Error"></span>
</form>

Get the value of the element inside the function.
Everything else seems to be working.
Here is the edited code.
let firstnameElement = document.querySelector("#inputfirst");
let form = document.querySelector('#loginform')
//form.addEventListener('submit', (e) => {
// e.preventDefault();})
function validation() {
let firstname = firstnameElement.value
if (firstname == "" || firstname == null || firstname == " ") {
document.querySelector("#inputfirst").classList.add("firstname")
document.querySelector("#firstname_Error").innerHTML = "firstname"
return false;
}
else {
document.querySelector("#inputfirst").classList.remove("firstname")
document.querySelector("#firstname_Error").innerHTML = ""
}
}
Also if your javascript file is linked at the head of the html make sure to add the defer attribute so it loads after the document.
<script src="test.js" defer></script>

Related

Is there a way to use prevent default and still receive post requests?

I am trying to properly validate form-data on my backend and still be able to have a nice user experience with form validation on my front end which is written in Javascript. I have all the form validation done on the front end, in order to get the effect we want we used e.PreventDefault() on our submit button so we can display any input errors to the user without a reload. The issue is when you actually fill out the form now and click submit there is no POST request being sent to the server because of the preventDefault.
Removing the line completely seemed to fix the problem of our server not receiving post requests but that creates the issue of the front end form validation being completely pointless because the error messages aren't displayed because of the refreshed page.
Javascript Front End Validation:
let btn = document.querySelector('.btn')
btn.addEventListener('click', function(e) {
e.preventDefault() // <---- THIS IS THE ISSUE
let firstName = document.querySelector('.firstName').value
let lastName = document.querySelector('.lastName').value
let email = document.querySelector('.email').value
let createPassword = document.querySelector('.createPassword').value
let verifyPassword = document.querySelector('.verifyPassword').value
let firstNameSubmit = false
let lasttNameSubmit = false
let emailSubmit = false
let createPasswordSubmit = false
let verifyPasswordSubmit = false
if (/^\s+$/.test(firstName) || firstName == null || firstName == '') {
document.querySelector('.firstNameError').innerHTML = 'First Name is a required field'
document.querySelector('.firstName').style.borderBottom = '1px solid red'
} else if (!/^\s+$/.test(firstName) || firstName !== null || firstName !== '') {
document.querySelector('.firstNameError').innerHTML = null
document.querySelector('.firstName').style.borderBottom = '1px solid #2ecc71'
firstNameSubmit = true
} if (/^\s+$/.test(lastName) || lastName == null || lastName == '') {
document.querySelector('.lastNameError').innerHTML = 'Last Name is a required field'
document.querySelector('.lastName').style.borderBottom = '1px solid red'
} else if (!/^\s+$/.test(lastName) || lastName !== null || lastName !== '') {
document.querySelector('.lastNameError').innerHTML = null
document.querySelector('.lastName').style.borderBottom = '1px solid #2ecc71'
lasttNameSubmit = true
} if (!/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
document.querySelector('.emailError').innerHTML = 'Please enter a valid email'
document.querySelector('.email').style.borderBottom = '1px solid red'
} else if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
document.querySelector('.emailError').innerHTML = null
document.querySelector('.email').style.borderBottom = '1px solid #2ecc71'
emailSubmit = true
} if (/^\s+$/.test(createPassword) || createPassword == null || createPassword == '' || createPassword.length < 6) {
document.querySelector('.createPasswordError').innerHTML = 'Password must be longer than 6 characters'
document.querySelector('.createPassword').style.borderBottom = '1px solid red'
} else if (!/^\s+$/.test(createPassword) || createPassword !== null || createPassword !== '' || createPassword.length >= 6) {
document.querySelector('.createPasswordError').innerHTML = null
document.querySelector('.createPassword').style.borderBottom = '1px solid #2ecc71'
createPasswordSubmit = true
} if (!createPasswordSubmit) {
document.querySelector('.verifyPasswordError').innerHTML = `Passwords don't match`
document.querySelector('.verifyPassword').style.borderBottom = '1px solid red'
} else if (verifyPassword == createPassword){
document.querySelector('.verifyPasswordError').innerHTML = null
document.querySelector('.verifyPassword').style.borderBottom = '1px solid #2ecc71'
verifyPasswordSubmit = true
}
Go Backend Halders:
http.HandleFunc("/signup", signupHandler) // inside func main()
func signupHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
tpl.ExecuteTemplate(w, "signup.html", nil)
fmt.Printf("METHOD: %s | URL: %v\n", r.Method, r.URL)
return
}
fmt.Printf("METHOD: %s | URL: %v\n", r.Method, r.URL)
r.ParseForm()
f := r.PostFormValue("fname")
l := r.PostFormValue("lname")
e := r.PostFormValue("email")
pw := r.PostFormValue("pass")
hash, err := helper.HashPassword(pw)
if err != nil {
fmt.Printf("Hashing Error")
}
fmt.Println("LoginValues")
fmt.Printf("%s\n, %s\n, %s\n, %s\n", f, l, e, hash)
}
Signup Template HTML:
<form action="/signup" method="post">
<h3>First Name</h3>
<input name="fname" type="text" class="firstName">
<p class="firstNameError"></p>
<h3>Last Name</h3>
<input name="lname" type="text" class="lastName">
<p class="lastNameError"></p>
<h3>Email</h3>
<input name="email" type="text" class="email">
<p class="emailError"></p>
<h3>Create Password</h3>
<input name="pass" type="password" class="createPassword">
<p class="createPasswordError"></p>
<h3>Verify Password</h3>
<input type="password" class="verifyPassword">
<p class="verifyPasswordError"></p>
<button class="btn" type="submit">Register</button>
</form>
I just want to know if there's a work around for front end with back end form validation either with preventDefault or if I need to approach the concept a different way if so how? Thanks in advance!
Because it's a type="submit" button, event.preventDefault() is preventing the "submit" event from firing (and the "submit" event is what sends the data to the backend).
Instead of listening for a "click" event on the button, I think it is better listen to a "submit" event on the form. It will be triggered on the form when you click a button with type="submit."
The form will now be the event's target.
let form = document.getElementById('my-form')
form.addEventListener('submit', function(event) {})
So, at the beginning of your function, you should be able to prevent the submit action by calling
event.preventDefault();
But, you can also store the form to a local variable, since that is the element that the submit event is triggering on:
let form = event.target
Then, if there are no errors, you can trigger the submit on the form at the end of your function:
form.submit()
all together:
let form = document.getElementById('my-form')
form.addEventListener('submit', function(event) {
event.preventDefault()
let form = event.target
let errors = false;
//do all of the error checking here, if there's an error, set errors to true
if(!errors) {
form.submit()
}
})
(There might be a better way, but that's what I could think of off the top of my head. Also, it might be easier to get all of the data values by adding a "name" attribute to each input, instead of querying each field).
I fixed the issue by messing around with #Maiya had provided. I took a step back and re-evaluated the javascript and what exactly was going on. Used a submit even listener and had basic form validation on the front end and now I can just ensure on the backend. I ended up using the e.preventDefault() right after I stored the form instance in a variable and then checked and submitted or it just shows the errors.
Javascript Changes:
let submit = document.getElementById("signupForm")
submit.addEventListener("submit", function(e){
let form = e.target // get form instance
e.preventDefault()
console.log(form)
// error handling
if (firstNameSubmit == false || lasttNameSubmit == false || emailSubmit == false || createPasswordSubmit == false || verifyPasswordSubmit == false) {
console.log('form not done')
} else { // form completed send to backend!
form.submit()
}
SignupHandler Changes:
user := &User{
fname: r.PostFormValue("fname"),
lname: r.PostFormValue("lname"),
email: r.PostFormValue("email"),
pw: r.PostFormValue("pass"),
}
user.hash = string(helper.HashPassword(user.pw))
//begin server validation
if user.fname == "" {
http.Redirect(w, r, "/signup", http.StatusBadRequest)
tpl.ExecuteTemplate(w, "signup.html", nil)
} else {
http.Redirect(w, r, "/login", http.StatusOK)
}
Instead of using Form method='post'(i.e., instead of using form to make post requests) just make a post request using axios. In that way it works even if there is event.preventDefault()

How to do simple client-side form validation using JavaScript/jQuery?

I was doing a project series on CodeCademy and I got a project in the series to do a client side form validation using JavaScript/jQuery.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
Age : <input type='text' id='age' placeholder='Age'><br><br>
Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
</form>
<button id='submit'>Submit</button>
</body>
</html>
My JavaScript/jQuery is:
$(document).ready(function()
{
var fname = document.getElementById('fname').val();
var lname = document.getElementById('lname').val();
var age = document.getElementById('age').val();
/*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/
$("#submit").click(function()
{
if(fname.length === 0)
{
alert("Please input a first name");
}
else if(lname.length === 0)
{
alert("Please input a last name");
}
else if(age.length === 0)
{
alert("Please input an age");
}
});
});
I don't need a very complicated code and please help me in the HTML department if something is wrong there or if something needs to be added there.
Also, I don't know how to get different elements in a class. I have put a comment in my jQuery regarding that so please help if you can.
This is a problem in a CodeCademy project and this is where a lot of newbies in JS and jQuery have a problem, so if you can help, it'll help a lot of people and not just me.
Thanks!
You need to use .value instead of .val() since you're using pure Javascript:
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if you want to use .val() method then you need a jQuery object:
var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();
You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:
$(document).ready(function () {
$("#submit").click(function () {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if (fname.length == 0) {
alert("Please input a first name");
} else if (lname.length == 0) {
alert("Please input a last name");
} else if (age.length == 0) {
alert("Please input an age");
}
});
});
Fiddle Demo
from your example, get elements by class name
var lists = document.getElementsByClassName("sex");
to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"
if you use native/pure javascript use .value not val() . val() is only for jquery
It looks like you're asking a couple questions at once.
As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.
I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.
As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.
Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/
One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.
Here is very simple way to make form validation using jquery
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: {
required: "Please provide a valid user name",
email: "Please enter a valid email address"
}
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
#import url("https://fonts.googleapis.com/css?family=Open+Sans");
/* Styles */
* {
margin: 0;
padding: 0;
}
body {
font-family: "Open Sans";
font-size: 14px;
}
.container {
width: 500px;
margin: 25px auto;
}
form {
padding: 20px;
background: #2c3e50;
color: #fff;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
form label,
form input,
form button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
form input {
height: 25px;
line-height: 25px;
background: #fff;
color: #000;
padding: 0 6px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
form button {
height: 30px;
line-height: 30px;
background: #e67e22;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
label.error {
color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
<h2>Registration</h2>
<form action="" name="registration">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john#doe.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="●●●●●" />
<button type="submit">Register</button>
</form>
</div>
function validate() {
var scheduledOn = $("#ScheduledOn").val();
var status = $(".Status option:selected").text();
var result = true;
if (id == "") {
var scheduledOn = $("#ScheduledOn").val();
var category = $(".categoryList option:selected").text();
var activityTask = $(".activityTaskList option:selected").text();
var lead = $("#LeadID").val();
var agent = $("#AgentID").val();
if (category == "Select Category") {
$("#categoryValidation").show();
$("#categoryValidation").text("The Category field is required");
}
else {
$("#categoryValidation").hide();
}
if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
var activityTask = $(".activityTaskList option:selected").text();
if (activityTask == "Select Activity Task") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
}
else {
$("#activityTaskValidation").hide();
}
}
if (category == "Joint Field Work") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Joint Field Work") {
if (lead == "" || lead == null || lead == "Select Lead") {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (category == "Agent Recruitment" || category == "Agent Development") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Direct Sales") {
if (lead == "" || lead == "Select Lead" || lead == null) {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (scheduledOn == "" || scheduledOn == null) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
}
return result;
}
else {
var scheduledOn = $("#NewScheduledOn").val();
var status = $(".Status option:selected").text();
if (document.getElementById("SetAppointment_Y").checked) {
var activityTask = $(".activityTaskList").val();
if (activityTask == null || activityTask == "") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
result = false;
}
else {
$("#activityTaskValidation").hide();
$("#scheduledOnValidation").hide();
}
if (status != null && (scheduledOn == "" || scheduledOn == null)) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
$("#statusValidation").hide();
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
$("#statusValidation").show();
}
}
}
return result;
}

How to change textContent via javascript?

I have a registration form page, and there is empty div i want to use to display errors. To check forms before triggering php script i use javascript:
function errorHandler(){
var loginIn;
var passIn;
loginIn = document.forms["regForm"]["login"].value;
passIn = document.forms["regForm"]["password"].value;
if (loginIn == "" || loginIn == null) {
alert("LOGIN CANNOT BE EMPTY");
return false;
}
}
It works fine, and alert message do appear when i call them like this:
<form name="regForm" action= "save_user.php" onsubmit="return errorHandler()" method="post">.
But there is as i mentioned before a div inside of the form: div id ="errorArea"></div> and when i try to put a text inside of this div like this:
function errorHandler(){
var loginIn;
var passIn;
var erorAreaMessage;
loginIn = document.forms["regForm"]["login"].value;
passIn = document.forms["regForm"]["password"].value;
erorAreaMessage = document.getElementById('errorArea').textContent;
if (loginIn == "" || loginIn == null) {
erorAreaMessage = "LOGIN CANNOT BE EMPTY";
return false;
}
}
Nothing happens, can someone explain me why?
You need to put the value inside the <div>. That can done by setting the innerHTML or textContent property to your error-message.
Try this -
...
if (loginIn == "" || loginIn == null) {
document.getElementById('errorArea').textContent = "LOGIN CANNOT BE EMPTY";
return false;
}}

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

How to write simplified and generic validation logics and rules in JQuery

I know there are tons of information out there over internet to validate form in JavaScript and JQuery. But I’m interested to write my own. Basically I want to learn this thing.
So here is my validation script I have written and its working fine.
function validate() {
var firstName = jQuery("#firstName").val();
var lastName = jQuery("#lastName").val();
var dateOfBirthy = jQuery().val("dateOfBirth");
if (firstName.length == 0) {
addRemoveValidationCSSclass("#firstName", false);
} else {
addRemoveValidationCSSclass("#firstName", true);
}
if (lastName.length == 0) {
addRemoveValidationCSSclass("#lastName", false);
} else {
addRemoveValidationCSSclass("#lastName", true);
}
}
function addRemoveValidationCSSclass(inputField, isValid) {
var div = jQuery(inputField).parents("div.control-group");
if (isValid == false) {
div.removeClass("success");
div.addClass("error");
} else if (isValid == true) {
div.removeClass("error");
div.addClass("success");
} else {
}
}
I want to achieve few things--
add validation message
More generic way to handle for every form.
And I want to add validation rule, like length, email validation,
date validation etc.
Now how can I achieve these?
Use jQuery validate. It does everything you want straight out of the box.
I did something similar to this, except that I wrote my rules in PHP since you need a server-side backup. When the PHP generates the form, it also generates some simple client-side validation that looks like this:
<!-- html field -->
<label for="first">
First Name: <input type="text" name="first" id="first">
<span id="first_message"></span>
</label>
Then the script is like this:
<script>
var formValid = true;
var fieldValid = true;
// Check first name
fieldValid = doRequiredCheck("first");
if (!fieldValid) {formValid = false};
fieldValid = doCheckLength("first", 25);
if (!fieldValid) {formValid = false};
function doRequiredCheck(id) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value === "") {
box.innerHTML = "**REQUIRED**";
}
}
function doCheckLength(id,len) {
var el = document.getElementById(id);
var box = document.getElementById(id + "_message";
if (el.value.length > len) {
box.innerHTML = "Too long";
}
}
</script>
Create a simple function:
function validations(day, hour, tap1, tap2, employed){
if( day== "" | hour== "" | tap1== "" | tap2== "" | employed== "" ){
return false;
} else {
return true;
}

Categories

Resources