javascript form validation_error in if condition - javascript

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>

Related

Having issues with field level validation using simple function

I am fairly new to coding so forgive me if it is something simple I am missing.
I am trying to validate the First Name field using a simple If statement in the function, but when I test it via live server the form submits without throwing the alert.
function validateForm() {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
return false;
} else {
return true;
}
};
firstNameValid(firstName);
};
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname" onsubmit="return firstNameValid(document.registration.fname)"><br>
</li>
<li>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="lname"><br>
</li>
<li>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
<script>
src = "app.js"
</script>
</body>
</html>
The script should be loaded into the page like this…
<script src="app.js"></script>
…not like this…
<script>
src = "app.js"
</script>
validateForm doesn't return anything - you probably just need to change
firstNameValid(firstName);
to
return firstNameValid(firstName);
But, I'm a little rusty on when a form does / does not end up submitting, you may need to do
function validateForm(e) {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
e.preventDefault();
return false;
} else {
return true;
}
};
return firstNameValid(firstName);
};
<form name="registration" action="page2.html" onsubmit="return validateForm(event)" method="GET">

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.

unable set required attribute to true with javascript

I have a form.When I submit that form the require attribute of the text field of that form should be set to true.I am trying this with javascript.But unable get the positive result.My code is
<html>
<head>
<script>
function validate()
{
alert("ok");
document.getElementById("sample").required = true;//method-1
document.getElementById("sample").setAttribute("required","")//method-2
}
</script>
</head>
<body>
<form method="post" action="" onsubmit="validate()">
<input type="text" id="sample">
<input type="submit" value="submit">
</form>
</body>
</html>
in both these methods I am unable to set required to true.any help please...
You can return on form submit like below example. This is reference url.
<form name="myForm" action="/action_page.php"onsubmit="return validateForm()" method="post">
See Demo
With element.required = true;
function validate() {
var el = document.getElementById("sample");
if (el.value) {
alert(el.value);
return true;
} else {
alert('Value is required..');
el.required = true; //method-1
return false;
}
}
<form method="post" action="#" onsubmit="return validate()">
<input type="text" id="sample">
<input type="submit" value="submit">
</form>
With element.setAttribute("required", "");
function validate() {
var el = document.getElementById("sample");
if (el.value) {
alert(el.value);
} else {
alert('Value is required..')
el.setAttribute("required", "");
return false;
}
}
<form method="post" action="" onsubmit="return validate()">
<input type="text" id="sample">
<input type="submit" value="submit">
</form>

Trying to post data with form, and check input field if empty

I'm trying to have a form where I can search a database, but also have simple error handling where I can check if the user did not enter anything and run the function validateForm. However I'm not sure how to do both.
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
Here's the script
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == null) {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
Instead of "null" in if condition simply use empty string like "".
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == "") {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
</body>
</html>

Something is going wrong with this onclick

<!DOCTYPE html>
<html>
<head>
<script>
function validateAlphaNumeric()
{
alert("function start");
var alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers="0123456789";
var flag=true;
var prod_id=document.getElementByID("productid").value;
alert(prod_id);
for(var i=0;i<prod_id.length;i++)
{
if(alphabets.indexOf(prod_id.charAt(i))==-1 || numbers.indexOf(prod_id.charAt(i)==-1)
{
alert("value must be alphanumeric");
break;
}
}
var prod_type=document.myform.producttype.value;
for(var i=0;i<prod_type.length;i++)
{
if(alphabets.indexOf(prod_type.charAt(i))==-1 || numbers.indexOf(prod_type.charAt(i)==-1)
{
alert("value must be alphanumeric");
break;
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://localhost:8080/examples/Submit.HTML" method="POST">
<br><br>
Prodcut ID:<input type="text" name="productid" id="productid" size="25" ">
<br><br>
Product Type:<input type="text" name="producttype" id="producttype" size="25" ">
<br><br>
</div>
<input type="submit" onclick="validateAlphaNumeric()" value="Submit">
</form>
</body>
</html>
This is a test page being written to only learn basics.When I am pressing Submit there is no checking happening and it goes to Submit.html page.why? What modification is needed here?
<input type="submit" onclick="validateAlphaNumeric()" value="Submit">
What exactly happens when I am pressing this button?
var prod_id=document.getElementByID("productid").value;
var prod_type=document.myform.producttype.value;
both mechanisms are same ?
This is the Modified one.But still not working. Please help
<!DOCTYPE html>
<html>
<head>
<script>
function validateAlphaNumeric()
{
var alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers="0123456789";
var flag=true;
var prod_id=document.getElementByID("productid").value;
for(var i=0;i<prod_id.length;i++)
{
if(alphabets.indexOf(prod_id.charAt(i))==-1 && numbers.indexOf(prod_id.charAt(i)==-1))
{
alert("value must be alphanumeric");
return false;
}
}
var prod_type=document.myform.producttype.value;
for(var i=0;i<prod_type.length;i++)
{
if(alphabets.indexOf(prod_type.charAt(i))==-1 && numbers.indexOf(prod_type.charAt(i)==-1))
{
alert("value must be alphanumeric");
return false;
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://localhost:8080/examples/Submit.HTML" method="POST">
<br><br>
Prodcut ID:<input type="text" name="productid" id="productid" size="25" ">
<br><br>
Product Type:<input type="text" name="producttype" id="producttype" size="25" ">
<br><br>
</div>
<input type="submit" onclick="validateAlphaNumeric(); " value="Submit">
</form>
</body>
</html>
there you go you forgot closing parenthesis for if statements:
<!DOCTYPE html>
<html>
<head>
<script>
function validateAlphaNumeric()
{
alert("function start");
var alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers="0123456789";
var flag=true;
var prod_id=document.getElementByID("productid").value;
alert(prod_id);
for(var i=0;i<prod_id.length;i++)
{
if(alphabets.indexOf(prod_id.charAt(i))==-1 && numbers.indexOf(prod_id.charAt(i)==-1))
{
alert("value must be alphanumeric");
break;
}
}
var prod_type=document.myform.producttype.value;
for(var i=0;i<prod_type.length;i++)
{
if(alphabets.indexOf(prod_type.charAt(i))==-1 && numbers.indexOf(prod_type.charAt(i)==-1))
{
alert("value must be alphanumeric");
break;
}
}
}
</script>
</head>
<body>
<form name="myform" action="" method="POST">
<br><br>
Prodcut ID:<input type="text" name="productid" id="productid" size="25" ">
<br><br>
Product Type:<input type="text" name="producttype" id="producttype" size="25" ">
<br><br>
</div>
<input type="submit" onclick="validateAlphaNumeric()" value="Submit">
</form>
</body>
</html>
if You want didn't go to Action page You must put return false; at end of onclick like this
onclick="validateAlphaNumeric();return false;"
or put return false; at end of function that you Call with return false; you say browser don't submit
Try returning false when validation fails

Categories

Resources