How to show text in id="result" When not a invalid email? - javascript

How to show text in id="result" When not a invalid email ?
http://jsfiddle.net/d65cdh2v/
When i fill not a valid email EG: xxxxxxx in input name="email"
i want to show text in id="result" EG: xxxxxxx not a valid
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
$("#result").text("");
$("#result").text(x + " not a valid :)");
return false;
}
else {
alert("OK");
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
<h2 id='result'></h2>
</body>
</html>

Your code works perfectly fine, provided you include jQuery: http://jsfiddle.net/d65cdh2v/1/
But I assume you aren't using jQuery, judging by the rest of your code, so to do it with vanilla JavaScript:
document.getElementById('result').innerHTML = x + " not a valid :)";
JSFiddle

Related

Form Validation against an Array with JavaScript/ jQuery

I've seen a couple answers on Stack but none of them detail how exactly this works. Currently I have a simple form with username and password forms which works with predefined values but not working when values are in an array. I want to use JS to validate the forms that both password and username match data points as strings within the forms. My code below has no errors to my knowledge, but my logic statements don't fire a correct entry. How can I fix this? (I included jQuery because I know a little bit in that realm and if it helps I'll take it.)
<!DOCTYPE html>
<html>
<head>
<title>Coding Project</title>
</head>
<body style="font-family:Helvetica">
<h1>
Simple Login Form:
</h1>
<form>
<input type="text" id="username" placeholder="Enter username" value=""> <br> <br>
<input type="password" id="password" placeholder="Enter password" value=""> <br> <br>
<button type="button" onClick="mySubmit()"> Submit
</button>
</form>
<script type="text/javascript">
function mySubmit() {
var userNameInput = document.getElementById("username").value;
var passWordInput = document.getElementById("password").value;
var existingUserName = [["46179"], ["55678"]];
var existingPassWord = [["helloworld123"], ["helloworld456"]];
if (userNameInput == existingUserName && passWordInput == existingPassWord) {
alert("Correct Username");
} else if (userNameInput == "" && passWordInput == "") {
alert("Empty field, please enter Username and Password or Signup");
} else {
alert("Incorrect Username or Password");
}
}
</script>
</body>
</html>
I just corrected your condition, please check this: (If username and password both found in existing array then it will be triggered the warning "Incorrect Username or Password")
Note: If it's not fulfill your requirement, then please let me know.
<!DOCTYPE html>
<html>
<head>
<title>Coding Project</title>
</head>
<body style="font-family:Helvetica">
<h1>
Simple Login Form:
</h1>
<form>
<input type="text" id="username" placeholder="Enter username" value=""> <br> <br>
<input type="password" id="password" placeholder="Enter password" value=""> <br> <br>
<button type="button" onClick="mySubmit()"> Submit
</button>
</form>
<script type="text/javascript">
function mySubmit() {
var userNameInput = document.getElementById("username").value;
var passWordInput = document.getElementById("password").value;
var existingUserName = ["46179", "55678"];
var existingPassWord = ["helloworld123", "helloworld456"];
if (!existingUserName.includes(userNameInput) && !existingPassWord.includes(passWordInput)) {
alert("Correct Username");
} else if (userNameInput == "" && passWordInput == "") {
alert("Empty field, please enter Username and Password or Signup");
} else {
alert("Incorrect Username or Password");
}
}
</script>
</body>
</html>

Can anyone tell my why this email validation is not working?

I am trying to get an email validation to work and can't seem to figure out the problem. I want it to alert if what is entered is not a valid email. The code I attached is the email function and the form code for the email. Help is appreciated thanks!
{
var emailfield=document.getElementById("emailaddress").value;
var atpos=emailfield.indexOf("#");
var dotpos=emailfield.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailfield.length){
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
}
Here is the code for the form.
<form action='#' method='post' name='f1' id="VPN" onsubmit='return checkButons(this)'>
Aspects <br>
<input type='radio' name='aspect' id='aspect1' value='security' />Security <br>
<input type='radio' name='aspect' id='aspect2'value='speed' /> Speed<br>
Features:<br>
<input type='checkbox' name='feat1' id='feat1'value='highspeedvpn' /> High Speed VPN <br>
<input type='checkbox' name='feat2' id='feat2' value='transactionguard' />Transaction Guard <br>
<input type='checkbox' name='feat3' id='feat3'value='antivirus' /> Antivirus Addon <br>
<h3 id="generaltext">Fill out your information below:</h3>
<p>
Name:<input name="Name"id='name'size=:50 type="text" required><br>
</p>
<p>
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required><br>
</p>
<p>
Street Address:<input name="S_Address"id='s_address'size=:50 type="text" required><br></p>
<p>
Address 2:<input name="Address_2"id='address_2'size=:50 type="text" required><br></p>
<p>
Zip Code:<input name="Zip"id='zip'size=:50 type="text" required><br>
<p>
City:<input name="City"id='city'size=:50 type="text" required><br>
You can use validation with regular exp -
var email = text_email.value;
var re = /^(([^<>()[\]\\.,;:\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 (re.test(email)) {
alert("Error msg");
return false;
}
Please see following. You can move validation logic to a different function.
JavaScript:
function checkButons(element) {
...
var emailfield = document.getElementById("emailaddress").value;
var atpos = emailfield.indexOf("#");
var dotpos = emailfield.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailfield.length) {
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
...
}
HTML:
<form action='#' method='post' name='f1' id="VPN" onsubmit='return checkButons(this)'>
....
<p>
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required><br>
</p>
....
</form>
Instead of using <input name="Emailaddress"id='emailaddress'size=:50 type="text" required> use type email, the browser will do the validations for you,but if you want to extra valdiate in server side you could use RegExp for it
Hi check this codepen https://codepen.io/anon/pen/BeeZBv?editors=1111
It is your JS code and it appears to be working, it may not be catching all possible conditions, but it is definitely working. Can you let me know what is not working?
Here is code
<input name="Emailaddress"id='emailaddress'size=:50 type="text" required>
<button onclick="validate()">Click me</button>
function validate() {
var emailfield=document.getElementById("emailaddress").value;
var atpos=emailfield.indexOf("#");
var dotpos=emailfield.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailfield.length){
console.log("Please enter a valid email address with an # and proper domain.")
return false;
}
}
Please keep a submit button on form,as I validated code form is not submitting once you having more input in a form and calling form event onSubmit and form is submitting with one field.
Function checkButons() {
var emailfield = document.getElementById("emailaddress").value;
var atpos = emailfield.indexOf("#");
var dotpos = emailfield.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= emailfield.length) {
alert("Please enter a valid email address with an # and proper domain.")
return false;
}
}
HTML Code :
<form action='#' method='post' name='f1' id="VPN" onsubmit="checkButons()">
Email Address:<input name="Emailaddress"id='emailaddress'size=:50 type="text" required>
Street Address:<input name="S_Address"id='s_address'size=:50 type="text" required>
<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.

javascript form validation_error in if condition

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>

JSP page's form not validating data with my Javascript

Issue
The problem is, that my JSP sends the form to my Servlet, without validating it with Javascript.
Javascript
function testInputText() {
var x, text;
x = document.getElementById("inputText").value;
if (typeof x != "string") {
text = "Invalid input JS";
document.getElementById("scriptError").innerHTML = text;
return false;
} else if(x ==""){
text = "No input found JS";
document.getElementById("scriptError").innerHTML = text;
return false;
} else {text = "Valid JS";
document.getElementById("scriptError").innerHTML = text;
return true;
}
}
formular.jsp
<!DOCTYPE html>
<html>
<head>
<script src="Javascripts/mailValidation.js"></script>
<title>Formular</title>
</head>
<body>
<form name="formular" onsubmit="return testInputText()" method="post"
action="/formSend" >
<fieldset>
<legend class="legendPersonal">Personal Information</legend>
<br>
<p class="formDescription"> fname: </p>
<p class="falseInput"> ${fnameF}</p>
<p id="sriptError"></p>
<input type="text" id="inputText" name="fname" value=${fname} >
<br>
<input type="submit" value="Send" >
</form>
</body>
</html>
My file formular.jsp is in a resource directory called "web". My javascript file in a subdirectory called "Javascripts" under "web" as well.
Denis you are trying to access scriptErrorwhereas you have not added the id into JSP page named with scripts.i think it was by mistake add as sriptError.
Updated JSP code :
<!DOCTYPE html>
<html>
<head>
<script src="Javascripts/mailValidation.js"></script>
<title>Formular</title>
</head>
<body>
<form name="formular" onsubmit="return testInputText()" method="post"
action="/formSend" >
<fieldset>
<legend class="legendPersonal">Personal Information</legend>
<br>
<p class="formDescription"> fname: </p>
<p class="falseInput"> ${fnameF}</p>
<p id="scriptError"></p>
<input type="text" id="inputText" name="fname" value=${fname} >
<br>
<input type="submit" value="Send" >
</form>
</body>
</html>
JS :
function testInputText() {
var x, text;
x = document.getElementById("inputText").value;
if (typeof x != "string") {
text = "Invalid input JS";
document.getElementById("scriptError").innerHTML = text;
return false;
} else if(x ==""){
text = "No input found JS";
document.getElementById("scriptError").innerHTML = text;
return false;
} else {text = "Valid JS";
document.getElementById("scriptError").innerHTML = text;
return true;
}
}
Good luck and let me know for any other help.

Categories

Resources