thanks in advance for answering the question.
The goal in my form (as with many similar forms) is to check that
text field is not empty
password meets the criteria (to be honest, right now I would be happy with just anything in it)
email has text before "#", the "#" and text after "#".
depending on whether all checks are okay, to display an alert with the message.
bootstrap:
<form>
<div class="form-group">
<label for="exampleTextarea">Course/Lecturer feedback</label>
<textarea class="form-control" id="textArea" rows="3" placeholder="Please enter your feedback in this field. Your opinion matters and helps us to provide you with better serivce."></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Please enter your email address</label>
<input type="email" class="form-control" id="emailAddress" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Please enter your password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" onclick="submitData()">Submit</button>
</form>
javascript
//comment validation function
function textFieldValidate(textField){
var txtln = "";
if (txtln !=="")
return pattern.test(textField);
}
//email validation function
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
//password validation function
// at least one number, one lowercase and one uppercase letter
// at least six characters
function passwordValidate(password){
var pw = new RegExp (/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/);
return pw.test(password);
}
function submitData(){
//retrieve the values
if(textFieldValidate(textField) && isValidEmailAddress(emailAddress) && passwordValidate(password)){
//send post request
alert("Thank you for your feedback! We have sent this to KGB and you should expect a call any moment now...");
}else{
//display error message
alert("Unfortunately information that you have entered was incorrect, please check the info and and resubmit");
return;
}
}
what I get at the moment is that my page refreshes and nothing happens.
Alright, it looks like the issue was with the id in html which was called textArea and in function I called it textField.
Now... the other problem is that it doesn't really validate anything. Just the pop up appears...
Related
I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!
This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is
<button type="submit" id="btn" onclick="validate()">login</button>
However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
HTML
<div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
JS
//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not
function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem
Firstly its not
document.getElementById('password');
value;
its
document.getElementById('password').value;
Secondly, there is no action property present I'll suggest removing the entire form tags
<div class="wrapper">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type=" submit" id="btn" onclick="validate()">login</button>
</div>
<script>
function validate() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
if (username == 'please' && password == 'work') {
alert('finally');
} else {
alert("NOOOO")
}
}
</script>
on your for, you are using attibute method="post" which has alternative of method="get" which being sent using URLs you are using method="post" which has a missing attribute action="/action_page.php" that will process you're page.
Like this
<form class="box" action="/action_page.php" method="post">
since you don't have action attribute, and has method="post", the post is being sent to the same page you are sending and without receiving it properly like in php.
$username = $_POST['username'];
If you still want to continue using javascript at test it, remove at post method, and remove the type="submit" on your button as it behaves on submitting if you just want to test using javascript.
Here is your final script.
HTML
<form class="box">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button id="btn" onclick="validate()">login</button>
</form>
</div>
JS
function validate(){
let username = document.getElementById('username').value;
let password=document.getElementById('password').value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I know that you use php to make logins with usernames and passwords but I'm still learning HTML, is there a way to make a form with one correct username and one correct password which are hardcoded using HTML or JS?
So for example if the user enters username abcd and password pass12345, then it goes to the next screen, otherwise it says "Sorry, password is incorrect."
This is just for learning purposes, I know it's not secure at all and shouldn't be used for actual websites. Just learning. Thanks :)
The login page right now...
<form action="loggedin.html">
<label for="username">Username</label>
<input
type="text"
placeholder="Enter Username"
name="username"
required
/>
<label for="password">Password</label>
<input
type="password"
placeholder="Enter Password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
DON'T EVER USE IN PRODUCTION - LEARNING PURPOSES ONLY
As this is for learning purposes only and you understand it's not secure, I have gone ahead and written a small snippet that will check against a hard coded username and password. If entered username or password do not match it will alert the user.
I have added comments through out the code to explain what I did and what's going on.
See below
<!--
Added onsubmit attribute to form so that it will trigger the JS function (authenticate).
if the function returns false it will prevent the form from submitting
-->
<form action="loggedin.html" onsubmit="return authenticate()">
<label for="username">Username</label>
<!-- added IDs to the inputs -->
<input
id="username"
type="text"
placeholder="Enter Username"
name="username"
required
/>
<label for="password">Password</label>
<input
id="password"
type="password"
placeholder="Enter Password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
<script>
//Following function gets values of the username and password fields and checks to see if they match a hard coded username and password
function authenticate(){
var authorised;
//get input values
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
//check to see if the password and username match
if(username == "abcd" && password == "pass12345"){
authorised = true;
}else{ // username or password do not match
authorised = false;
//alert user
alert("Sorry, password is incorrect.");
}
//return result
return authorised;
}
</script>
I'm having an issue figuring out how to write the following code:
the problem is that I'm using an empty <div> with the id error-display. This <div> is where the error messages will be inserted when the errors that they represent occur. I want to make all fields validated when the user clicks off of them to the next field. If there’s an error, an error message should be displayed. Likewise, error messages should be removed when the user fixes the problem. yet I'm not sure how to do it! here is what I got so far:
<div id="error-display">
</div>
<form id="project-form">
<br>E-mail:<span class="error">* </span>
<input type="email" name="email" id="email" placeholder="Example#example.com" required>
<br>Password:<span class="error">* </span>
<input type="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="password" required>
<br>Confirm Password:<span class="error">* </span>
<input type="password" placeholder="Repeat Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="password-confirmation" required>
After inserting the emipty "div id="error-display">" what can I do?
lets say the error message is: Invalid email address.
<input type="email" name="email" id="email" placeholder="Example#example.com" required>
I tried "required" in the input elements and it's working for my inputs, however, I think my professor is looking for a different solution.
I suggest you to add change event listener for every input field and to validate each of them and if some are invalid you should set innerText property of the 'error-display' div to error message text
Here's a quick and simple solution for you
in all of your input fields, put onchange="validateField(fieldID, fieldname)" like this
<input type="email" name="email" id="email" onchange="validateField('email', 'Email')" placeholder="Example#example.com" required>
then paste this script below your form (or you can have this in a separate js file)
<script>
function validateField(fieldID, fieldname) {
var inpObj = document.getElementById(fieldID);
if (!inpObj.checkValidity()) {
document.getElementById("error-display").innerHTML = "Invalid " + fieldname + ":" + inpObj.validationMessage;
} else {
//this will clear your error if the input is already correct
document.getElementById("error-display").innerHTML = "";
}
}
</script>
I have a registration webpage where a user inputs information like name and password. There are two inputs for password to verify they are the same password but when I submit the form, it says the passwords don't match, even when they do.
<form id="registration-info" method="POST" action="/registration" >
...
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
<script>
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
repeat_password.setCustomValidity('');
}
}
</script>
</div>
There are two problems with your code.
You've put your validation code in an onclick handler on the <form> element. This means the script will never run at all, because the user doesn't click on the <form>, they click on the submit <button>. Instead use an onsubmit handler on the form.
You aren't doing anything to prevent the form from submitting if the password values don't match. One way to do this is to return false from the onsubmit handler.
Here is a corrrected version:
form = document.getElementById("registration-info");
form.onsubmit = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if (password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
console.log("Passwords don't match");
return false; // prevent the form from submitting
} else {
repeat_password.setCustomValidity('');
}
}
// reset the customValidity when the field is modified, so corrected
// values won't trip up on past errors:
document.getElementById("repeat_password").onchange = function(e) {
e.target.setCustomValidity('')
}
.invalid-feedback {display:none}
<form id="registration-info" method="POST" action="/registration">
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
</div>
<input type="submit" value="Submit" id="registration-info-submit">
</form>
Another way to do this -- and to be honest if I'd been familiar with setCustomValidity before this question, this probably would have been my answer in the first place -- might be to set the customValidity message values when the field values change, instead of on form submit. (If a customValidity value is set, it will prevent the form submit from running at all.)
document.getElementById("registration-info").onchange = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if (password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
repeat_password.setCustomValidity('');
}
}
<form id="registration-info" method="POST" action="/registration">
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
</div>
<input type="submit" value="Submit" id="registration-info-submit">
</form>
(But note that this will leave your forms unvalidated in IE9 and below, which do not support setCustomValidity; the first snippet will validate the form in all browsers.)
You did not take the values of the selected ids here. Inatead of taking values after in IF case try the following code. I hope that is the only reason.
var password = document.getElementById("password").value;
var repeat_password = document.getElementById("repeat_password").value;
This question already has answers here:
Strip white spaces on input
(4 answers)
Closed 6 years ago.
I have a signup form that requires an email. when a user uses an android device and enters their email, if they have used the device before android auto suggests their email. If the user selects the auto suggestion it ads a trailing blank space at the end. then when the user goes to signup the system says invalid email because of the blank space. users dont always see the blank space. How can I remove the trailing blank space automatically.
I already have a piece of js that uses the check this function to compare email address entered for repeat email.
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail');
var emailRepeat = document.getElementById('eMail_repeat');
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
var email = document.getElementById("eMail").value.trim();
var repeat = document.getElementById("eMail_repeat").value.trim();
demo can be found here. Enter whitespace after the email inputs to check.
edit: Clearer demo can be found here, with sample addresses provided, and highlighting the differences between using .trim() and not using it.
you can use $.trim() function here:
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail').value.trim();
var emailRepeat = document.getElementById('eMail_repeat').value.trim();
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
You can use Javascript's String.replace with this regex /\s+$/. It would replace the text with empty string.
string.replace(/\s+$/, '')
Example:
var testString = " test string ";
console.log(testString.replace(/\s+$/, ''); // logs: " test string"
DEMO
Note: We could have used the trim() function directly but it removes leading as well as trailing spaces whereas we want only trailing. trimLeft and trimRight are neither standerdized nor implemented in all browsers.
Just use the Jquery snippet below so that, even if you select an email with spaces, it will be trimmed using the input bind event.
It even will not allow spaces.
$(function(){
$('#eMail').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
$('#eMail_repeat').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="email" id="eMail"/>
<input type="email" id="eMail_repeat"/>
Pls run the code snippet, paste any email with spaces directly, and it automatically trim's the spaces.
Here is a fiddle