I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd
Related
Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>
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>
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.
I want to add cursor after empty input into form element. Where first empty form are.
With this goal I tryed to add this.focus(); into validate() function. But this wasn't succeeded.
And second point - how to set cursor after emerges page at brovser to first form element. I tryed with this target onLoad(); method into body. But this wasn't succeeded.
Code:
<html>
<head>
<title>Form with check</title>
<script>
function validate() {
if(document.form1.yourname.value.length < 1) {
alert("Enter your name, please");
this.focus();
return false;
}
if(document.form1.adress.value.length < 3) {
alert("Enter your adress, please");
this.focus();
return false;
}
if(document.form1.phone.value.length < 3) {
alert("Enter your phone number, please");
this.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Form with check</h1>
<p>Input all data. When button Submit pushed data will be sent as message.</p>
<form name="form1" action="mailto:user#host.com" enctype="text/plain"
onSubmit="validate();">
<p><b>Name:</b><input type="text" length="20" name="yourname">
</p>
<p><b>Adress:</b><input type="text" length="20" name="adress">
</p>
<p><b>Phone:</b><input type="text" length="20" name="phone">
</p>
<input type="SUBMIT" value="Submit">
</form>
onLoad();
</body>
</html>
Question:
How to add this functionality to form?
didn't you forget to do
onSubmit="return validate();" ?
Replace this.focus() with document.form1.yourname.focus();
Here is the re-worked code:
<html>
<head>
<title>Form with check</title>
<script>
function validate() {
if(document.form1.yourname.value.length < 1) {
alert("Enter your name, please");
document.form1.yourname.focus();
return false;
}
if(document.form1.adress.value.length < 3) {
alert("Enter your adress, please");
document.form1.adress.focus();
return false;
}
if(document.form1.phone.value.length < 3) {
alert("Enter your phone number, please");
document.form1.phone.focus();
return false;
}
document.getElementById("ff").submit();
return true;
}
</script>
</head>
<body >
<h1>Form with check</h1>
<p>Input all data. When button Submit pushed data will be sent as message.</p>
<form id="ff" name="form1" action="mailto:user#host.com" enctype="text/plain"
>
<p><b>Name:</b><input type="text" length="20" name="yourname">
</p>
<p><b>Adress:</b><input type="text" length="20" name="adress">
</p>
<p><b>Phone:</b><input type="text" length="20" name="phone">
</p>
<input type="button" value="Submit" onclick="validate();">
</form>
</body>
</html>
And the Working DEMO too
onSubmit="validate();"
In the context of your validate function this will be the global window object.
To handle the form in the function, based on your code, you can call it manually using document.form1 or by id (or other selector), or you can send the form to the function:
<script>
function validate(sender) {
if(sender.yourname.value.length < 1) {
alert("Enter your name, please");
sender.focus();
return false;
}
if(sender.adress.value.length < 3) {
alert("Enter your adress, please");
sender.focus();
return false;
}
if(sender.phone.value.length < 3) {
alert("Enter your phone number, please");
sender.focus();
return false;
}
return true;
}
</script>
<form name="form1" action="mailto:user#host.com" enctype="text/plain" onSubmit="validate(this);">
<p>
<b>Name:</b><input type="text" length="20" name="yourname">
</p>
<p>
<b>Adress:</b><input type="text" length="20" name="adress">
</p>
<p>
<b>Phone:</b><input type="text" length="20" name="phone">
</p>
<input type="SUBMIT" value="Submit">
</form>
I've this code:
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body>
<form name="frm" action="test.php">
Enter name:<input type="text" name="name" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit"/>
</form>
</body>
</html>
In above code, I'd tried to validate textfields when they lose focus. The script working fine if the name starts with A. But I want if the user enter different name which doesn't start with A it will return the focus to the textfield name. For that I'd written this script:
<script type="text/javascript">
var name = document.frm.name.value;
if(name.indexOf("A") == 0){
alert(name);
}else{
document.frm.name.focus();
}
</script>
then it doesn't works.
Anybody could help with that what should I do to request focus of textfield name?
I've only a little knowledge of javascript.
Just give an id for you form and refer it with document.getElementById('form_id'). Use of name attribute in this context has been deprecated over a decade ago. Also name for input should be something else than "name", rather use username or sth.
HTML:
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" id="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" id="email" onblur=""/>
</form>
JavaScript:
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
Instead of retrieving the id of the form, you can also pass the form to validate() as an argument: onblur="validate(this);". Then use that argument as a form in the eventhandler:
function validate(form){
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
EDIT
Focus doesn't seem to work without a delay, you can try this (the inputhas an id="username"):
function focusTo (elm) {
elm.focus();
return;
}
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
alert('error');
setTimeout(function () {focusTo(form.username);}, 10);
}
}
modifiy your script like this
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body >
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit" onclick="check()"/>
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
alert(name);
document.getElementById('frm').email.focus();
}else{
document.getElementById('frm').username.focus();
}
}
function check()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
}else{
alert("Please enter a name starting with 'A'");
document.getElementById('frm').username.focus();
}
}
//-->
</SCRIPT>
</body>
</html>
You want to execute function validate() on event onblur. in the script you have written the code for focusing, but not added it in a function.
try this document.frm.username.focus(); . i hope it will work.