JavaScript Validation Form / Not Working - javascript

Absolute newbie here - I'm super passionate about coding and just started with Javascript last week...I cannot seem to get this validation to work! Thanks in advance for all your good advice
-S
<script type="text/javascript">
//Registration Form Validation
function validate(){
var firstName=document.getElementById("name").value;
var maleUser = document.getElementById("maleButton").checked;
if(firstName=="" || firstName==" "){
alert("Please enter your first name: ");
return false;
}
else if(maleUser==false){
alert("Please select your gender: ");
}else{
return true; window.location.href="Search/index.htm";
</script>
<!-- Reg Form needing validation -->
<h1>Registration Form</h1>
<p>
<div class=form_settings>
<form name="RegForm" onsubmit="return(validate());" >
First name: <input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
<br>
Gender:
<input type="radio" name="male" id="maleButton" value="male"> Male
<br>
</p>
</form>

Please correct your HTML code:
<h1>Registration Form</h1>
<div class="form_settings">
<form name="RegForm" action="search/index.htm">
First name:
<input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
<br>
Gender:
<input type="radio" name="male" id="maleButton" value="male"> Male
<br>
<input type="submit" value="submit" onclick="return(validate());">
</form>
</div>
Add this updated JavaScript code:
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
function validate(){
var firstName = document.getElementById("name").value;
var maleUser = document.getElementById("maleButton").checked;
if (trim(firstName) === ''){
alert("Please enter your first name: ");
return false;
}
else if(maleUser == false){
alert("Please select your gender: ");
return false;
}
else{
//window.location.href="Search/index.htm";
return true;
}
}
You can see a complete result here: https://jsfiddle.net/logual/ba5f7tkw/
Don't use window.location.href to submit form. Add an action attribute with url and a submit button to your form.

I ran your code and got
Uncaught SyntaxError: Unexpected end of input
on line 20
you're missing a } after your else
else{
return true; window.location.href="Search/index.htm";
Protip: Run in chrome and type CTRL-SHIFT-J

Related

I need to add a message box and e-mail textbox and display everything in my form in the msgresults tag

I need to add a message box and e-mail textbox and display everything in my form in the 'msgresults' tag.
I need to add a Message box and and e-mail text box. Then I need all information to be shown within the MsgResults tag. The radioboxes already are shown this way.
function validateForm(){
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name == "" || name == null){
resultsMsg("We need your name please");
}else{
if(age == "" || name == null || isNaN(age)){
resultsMsg("Please enter a number for your age");
}else{
if(!getSkill()){
resultsMsg("Please select the type of problem you are having.");
}else{
resultsMsg("Type of Problem: " + getSkill());
}//end else
}// end function
}
}
function getSkill(){
var isChecked = false;
var theSelection;
var skills = document.getElementsByName('skillset');
for (var i=0; i < skills.length; i++){
if(skills[i].checked){
isChecked = true;
theSelection = skills[i].value;
break;
}
}
if(isChecked){
return theSelection;
}else{
return false;
} // end else
} // end function
function resultsMsg(s){
var resultsBox = document.getElementById("results");
resultsBox.innerHTML=s;
} // end function
<form name="form1" id="form1" action="" method="post">
<label>Full Name:
<input type="text" id="name" name="name">
</label>
<br> <!-- new line here -->
<label>Your Age:
<input type="text" id="age" name="age">
</label>
<br> <!-- new line here -->
<input type="radio" name="skillset" value="Technical Issues">Technical Issues</br>
<input type="radio" name="skillset" value="Recovery Issues">Recovery Issues</br>
<input type="radio" name="skillset" value="Hardware Issues">Hardware Issues</br>
<input type="radio" name="skillset" value="Software Issues">Software Issues</br>
<input type="radio" name="skillset" value="Software Crashes">Software Crashes</br>
<input type="radio" name="skillset" value="Hardware Malfunctions">Hardware Malfunctions</br>
<input type="radio" name="skillset" value="General Problems">General Problems</br>
<input type="button" value="Submit" onClick="validateForm();"> <input type="reset" value="Clear Form">
</form>
<div id="results"></div>
If I understand your goal correctly, you want to add the given name and age to the result-div, on top of the 'Type of Problem' that is already show. That can be easily achieved by adding the correct variables to the last else-loop in your validateForm function. Something among the following should probably work:
resultsMsg("Name: "+name+ "<br>Age: " +age+ "<br>Type of Problem: " + getSkill());

Inserting regular expression for verifying URL address and email address

I need to insert a regular expression to verify the input for URL and email is valid, so where would this go in the code to make it work without messing with anything else? I need to know exactly where it would go and how it would look.
window.onload = function() {
document.getElementById('ifBusiness').style.display = 'none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if (is_business) {
document.getElementById('ifBusiness').style.display = 'block';
document.getElementById('ifResidence').style.display = 'none';
} else {
document.getElementById('ifBusiness').style.display = 'none';
document.getElementById('ifResidence').style.display = 'block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if (address.value == "") {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the bname, tax and url if a business is selected
if (is_business) {
if (bname.value == "") {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
if (tax.value == "") {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if (url.value == "") {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if (rname.value == "") {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if (email.value == "") {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open('', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusb ar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234');
// Set the form target to the name of the newly created popup.
var form = document.querySelector('form[name="myForm"]');
form.setAttribute('target', 'SELU');
return true;
}
head {
text-align: center;
}
body {
text-align: center;
}
.bold {
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h1>Fill the form below</h1>
<!-- center tag is deprecated and should be replaced by CSS -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="text" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
<hr>
<hr>
</body>
</html>
To validate whether or not a user is inputting an url/email, simply change your input type to "url" or "email" and it will be validated for you.
Like so:
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="url" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="email" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>

Javascript Validation doesnt work in my Spring boot

As i try to do javascript validation but it dosent work on click of submit button
my Js Code : validation.js which is inside resource/static/js/validate.js
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
if(!hasEmailError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
my jsp code : registration.jsp
<script type="text/javascript" src="/js/validate.js"></script>
</head>
<body>
<form action="regUser" method="post" id="form">
First Name<input type="text" name="user_fname"><br>
Last Name<input type="text" name="user_lname"><br>
Email <input type="text" name="email"><br>
<font id="emailError" style="color: red;">${emailExistError} </font>
Contact No<input type="text" name="contactno"><br>
Password<input type="password" name="user_password"><br>
<input type="submit" onclick="return validate()" value="SUBMIT">
</form>
</body>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=pass#1234
spring.jpa.show-sql=true
spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/hotelmgmt
spring.main.allow-bean-definition-overriding=true
server.port = 8090
pls tell where am i missing the point?
You need put <script type="text/javascript" src="/js/validate.js"></script> before close body tag instead of head tag.
Put this line in one line.
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Current code show error "Uncaught SyntaxError: Invalid regular expression: missing /"
I tried reproduce your code, it worked
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
if(!hasEmailError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
<body>
<form action="regUser" method="post" id="form">
First Name<input type="text" name="user_fname"><br>
Last Name<input type="text" name="user_lname"><br>
Email <input type="text" name="email"><br>
<font id="emailError" style="color: red;"></font>
Contact No<input type="text" name="contactno"><br>
Password<input type="password" name="user_password"><br>
<input type="submit" onclick="return validate()" value="SUBMIT">
</form>
</body>
I think it would be helpful for you to first simplify the return statements.
The hasError = !false is very confusing.

HTML Form - Form keeps validating everything at once

I'm having validation problems with a HTML form I created. It seems to be running all the validation checks when I validate the first input without entering anything into the second input. I want it so when I finish entering the first input, it validates only that one. Then I can repeat the same process to the second input. Once both inputs are correctly validated then the user can submit.
I've recreated what I have in a JSFiddle which can be found here: http://jsfiddle.net/aJ2Tw/220/. Any help would be appreciated!
Code:
<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">
<div class="input-wrapper">
<input type="text" placeholder="First Name" id="firstname" name="name"/>
<input type="text" placeholder="First Name" id="lastName" name="name"/>
</div>
Submit
<script>
function FormValidation(){
//First Name Validation
var fn=document.getElementById('firstname').value;
if(fn == ""){
alert('Please Enter First Name');
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
if (/^[0-9]+$/.test(document.getElementById("firstname").value)) {
alert("First Name Contains Numbers!");
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
if(fn.length <=2){
alert('Your Name is To Short');
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
}
</script>
You can create create flags which will keep track of if a input field has been touched/changed once. Then in your FormValidation method you can only validate/display error only for the fields which have been touched/changed.
<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">
<div class="input-wrapper">
<input type="text" onchange="input1Changed()" placeholder="First Name" id="firstname" name="name"/>
<input type="text" onchange="input2Changed()" placeholder="First Name" id="lastName" name="name"/>
</div>
Submit
<script>
function FormValidation(){
if(isInput1Changed)
{
//validations/errors of Firstname
}
if(isInput2Changed)
{
//validations/errors of lastname
}
}
var isInput1Changed = false;
var isInput2Changed = false;
function input1Changed(){
isInput1Changed = true;
}
function input2Changed(){
isInput2Changed = true;
}
</script>
Hope you get the point!

Validating form after error has been shown

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Categories

Resources