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.
Related
<html>
<head>
</head>
<body>
<script>
function myFun(){
var correct_way = /^[A-Za-z0-9]+$/;
var a = document.getElementById("User_Name").value;
if(a=="") {
document.getElementById("Message").innerHTML="Please enter a username.";
return false;
}
if(a.length<5){
document.getElementById("Message").innerHTML="Please enter a username with 5 or more characters";
return false;
}
if(a.match(correct_way))
document.location.href = "test1.html";
else{
document.getElementById("Message").innerHTML="Please enter a username with only letters and integers";
return false;
}
}
</script>
<form onsubmit="return myFun()">
<input type="text" id="User_Name" value=""></input>
<br></br>
<span id="Message"> </span>
<br></br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>
Hello, I have created a username validation code. The validation does work however, the user is not redirected to the 'test1.html' document. They are both in the same folder. How do i make it redirect after the validation is checked?
You should return true at the end of function myFun.
HTML
<form action="test1.html" onsubmit="return myFun()">
<input type="text" id="User_Name" value="" />
<span id="Message"> </span>
<input type="submit" value="Submit" />
</form>
Updated code
function myFun(){
var correct_way = /^[A-Za-z0-9]+$/;
var a = document.getElementById("User_Name").value;
if(a=="") {
document.getElementById("Message").innerHTML="Please enter a username.";
return false;
}
if(a.length<5){
document.getElementById("Message").innerHTML="Please enter a username with 5 or more characters";
return false;
}
if(a.match(correct_way)){
alert("Sucessful Login, welcome to BREAKOUT!");
}
else{
document.getElementById("Message").innerHTML="Please enter a username with only letters and integers";
return false;
}
return true;
}
jsFiddle demo - http://jsfiddle.net/h67q09mp/
I have my form in Spring MVC into which I need to apply java script validations as well. The code is given below.
function validate_form() {
valid = true;
var fname = document.myform.firstname.value;
if (fname == "") {
document.getElementById('fname_error').innerHTML = "enter the first name";
valid = false;
}
return valid;
}
<html>
<head></head>
<body>
<form:form action="done" method="post" modelAttribute="student" name="myform" onsubmit="return validate_form()">
<p>First name:</p>
<form:input type="text" path="firstname" name="firstname" />
<p id="fname_error"></p>
<input type="submit" value="Sumbit">
</form:form>
</body>
</html>
Here the java script code executes, but the if condition does not executes. Is this problem need to be solved using the controller class? Please help me in this matter.
thank you.
I think you are adding :form there which was not necessary.
Here is the running code:
<html>
<head></head>
<body>
<form action="done" method="post" modelAttribute="student" name="myform" onsubmit="return validate_form()">
<p>First name:</p>
<input type="text" path="firstname" name="firstname" />
<p id="fname_error"></p>
<input type="submit" value="Sumbit" >
</form>
<script type="text/javascript">
function validate_form(){
valid = true;
var fname = document.myform.firstname.value;
if(fname == ""){
document.getElementById('fname_error').innerHTML = "enter the first name";
valid = false;
}
return valid;
}
</script>
</body>
</html>
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
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;
}
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.