Validation through getElementById() - javascript

I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("Don leave blank!")
return false;
}
if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("invalid");
return false
}
return true; //doesn't go to next.php
}
My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.

Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
^-----------should be removed
so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
For preventing submition,when input is invalid, you can try something like a:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
alert("Correct")
else {
alert("Don leave blank!")
return false;
}
if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
alert("Correct")
else {
alert("invalid");
return false;
}
}
//Borrowed from jQuery lib
function isNumeric( obj ){
return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>

Try this,
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") {}
else {alert("Don leave blank!"); return false;}
if (isNaN(Tel)){ alert("invalid"); return false;}
else { }
return true;
}
Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>
Use return false to prevent submitting form in case of any validation errors.

Related

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.

Check required inputs with javascript

I have 4 inputs on my page, and on a button onClick, i want to check, that all the inputs are filled with text.
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="text" value="" id="input3">
<input type="text" value="" id="input4">
What i want : Store all the required inputs ID in an array, and on click, check, that is there any input, that is empty.
How can i do this at the simplest way?
Use required tag instead as given below
<input type="text" value="" id="input1" required>
you can also try adding REGEX for more strict checking
// using Plain JavaScript
var input1= document.getElementById('input1').value;
if(input1 == "" ){
alert("Input 1 is Empty");
return false;
}
var input2 = document.getElementById('input2').value;
if(input12 == "" ){
alert("Input 2 is Empty");
return false;
}
var input3 = document.getElementById('input3').value;
if(input3 == "" ){
alert("Input 3 is Empty");
return false;
}
var input4 = document.getElementById('input4').value;
if(input4 == "" ){
alert("Input 4 is Empty");
return false;
}
just incase the required attribute fails.. you can do this..
add a validate function to the blur event, that is when the user leaves the field..
<input type="text" onblur="validate(this)" value="" id="input1">
<input type="text" onblur="validate(this)" value="" id="input2">
<input type="text" onblur="validate(this)" value="" id="input3">
<input type="text" onblur="validate(this)" value="" id="input4">
<button> ... </button>
and using jquery you can do this..
function validate(obj){
if($(obj).val() == ''){
alert('this Field cannot be empty');
$(obj).focus(); //send focus back to the object...
}
}
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="text" value="" id="input3">
<input type="text" value="" id="input4">
jQuery(function($){
var arr = [];
// number of input elements
var count = $("input").length;
// store list of input ids
$("buttonName").on('click', function(event) {
$("input").each(function(i){
var currId = $(this).attr('id');
arr.push(currId);
if ($(this).val()=="") {
alert(currId+": has no input");
}
});
});
});

The id-selector does not work within php

my javascript won't respond to my id-tag within php code:
else {
echo '<form = "nav-login" method="post" onsubmit="return noEmptyUserFields();" action="includes/login.inc.php">
<input type="text" id="uidz" name="uid" placeholder="Username/e-mail">
<input type="password" id="pwdz" name="pwd" placeholder="password">
<button type="submit" name="submit">Login</button>
</form>
Sign up';
}
But it responds to my javascript which is outside of the php which looks like this:
<form class="signup-form" method="post" onsubmit="return noEmptyUserFields();" action="includes/signup.inc.php">
<input type="text" id="first" name="first" placeholder="Firstname">
<input type="text" id="last" name="last" placeholder="Lastname" >
<input type="email" id="email" name="email" placeholder="E-mail" >
<input type="text" id="uid" name="uid" placeholder="Username" >
<input type="password" id="pwd" name="pwd" placeholder="Password" ></p2>
<button type="submit" name="submit">Sign up</button></form>
How come it won't respond to the id-selector within php?
I have included <script src="includes/javascript.js"></script>
on both.
My javascript looks like this (noEmptyLoginFields) :
if (email.trim().length < 1)
{
alert('Email must be filled out');
return false;
}
else if(pwd.trim().length < 6)
{
alert('Password must contain atleast 6 characters');
return false;
}
else if (first.trim().length < 1)
{
alert('First name must be filled out');
return false;
}
else if (last.trim().length < 1)
{
alert('Last name must be filled out');
return false;
}
else if (uid.trim().length < 1)
{
alert('Username must be filled out');
return false;
}
else return true;
}
function noEmptyLoginFields()
var uidz = document.getElementById('uidz').value;
var pwdz = document.getElementById('pwdz').value;
if (uidz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
else if(pwdz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
}
You seem to be using the same function name for both form validations, which is causing the error. I advise you to handle form validation purely in javascript using event handlers:
document.querySelector("#formId").addEventListener("submit", function() {
// if(...) return false;
});

How can i validate and alert if the phone has incorrect input?

The phone number and the email must be valid.
This is a basic popup contact form without the phone number validation. I would like to validate the phone number. I heard about regex but i´m not sure how to implement in the code.
Since i don´t understand javascrip yet i hope you can help me.
<form action="#" method="post" id="form">
<h2>Contact Us</h2><hr/>
<input type="text" name="company" id="company" placeholder="Company"/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<input type="text" name="phone" id="email" placeholder="Phone"/>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
function check_empty(){
if(document.getElementById('company').value == ""
|| document.getElementById('name').value == ""
||document.getElementById('email').value == ""
||document.getElementById('phone').value == "" ){
alert ("Please, fill the fields!");
}
else {
document.getElementById('form').submit();
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}

After Javascript Validation page redirect to another page

i have tryed to validate textbox using javascript.when i click on the submit button without inserting values to textbox it's display alert box.but after click on "ok" button , page redirect to payments.php page.how to fix it
<form method="post" action="payments.php" >
First Name : <br />
<input name="name" type="text" class="ed" id="name" /> <br />
E-mail : <br />
<input name="email" type="text" class="ed" id="email" /> <br />
<input name="but" type="submit" value="Confirm" onclick="Validation()" />
</form>
function Validation()
{
if (checkFName()&&checkemail())
{
window.event.returnValue = false;
}
}
function checkFName()
{
var tname = document.getElementById("name").value;
if((tname == null)||(tname == ""))
{
alert("Please Enter your First name");
return false;
}
return true;
}
function checkemail()
{
var email = document.getElementById("email").value;
var ap = email.indexOf("#");
var dp = email.lastIndexOf(".");
if((ap < 1)||(dp-ap < 1)||(dp >= email.length-1))
{
alert("invalid email address");
return false;
}
else
return true;
}
You need to change the CONFIRM button type to "button":
<input name="but" type="button" value="Confirm" onclick="Validation()" />
Give your form a name:
<form name="frm" method="post" action="payments.php">
then in your Validation() function, if your form passes validation, you can do the following:
function Validation()
{
if (checkFName()&&checkemail())
{
document.forms["frm"].submit();
}
}

Categories

Resources