Check whether an HTML input has been completed - javascript

I am trying to program a login / register system with LocalStorage, HTML and Javascript. Now I want to check whether an HTML input element has been filled in or whether it is OK. I have not found a suitable post for this. Can someone help me?
HTML code:
<input id="register-input1" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="Given name" name="ri1">
<input id="register-input2" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="Surname" name="ri2">
<input id="register-input3" name="ri5" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="E-Mail address">
<input id="register-input4" type="password" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="Password" name="ri3">
<input id="register-input5" type="password" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="Repeat Password" name="ri4">
Javascript Code:
var givenname = document.getElementById('register-input1');
var surname = document.getElementById('register-input2');
var email = document.getElementById('register-input3');
var password = document.getElementById('register-input4');
var password2 = document.getElementById('register-input5');
function storeRegisterData() {
localStorage.setItem('givenname', givenname.value);
localStorage.setItem('surname', surname.value);
localStorage.setItem('email', email.value);
}
function checkRegisterData() {
if(password.value !== password2.value) {
alert('The first password does not match the second!')
}else{
--The review should be here!--
}
}
(Translated with Google translated, errors could be included!)

You can use
<input type="text" required>
or
you can simply use javascript :
function checkRegisterData() {
if(password.value !== password2.value) {
alert('The first password does not match the second!')
}else
{
if(givenname.value == NULL)
{
alert("Name field Empty");
}
}
}

You can use required attribute to make sure that the input feild is filled.
You can also use min-length and max-length to make sure that the length of the input matches the required length that you would like to be entered.
Example:
<input type="text" required="required" min-length="4" max-length="4923" />
(here the user must type in some text between 4 and 4923 characters long)

Related

why is my validation in password not working when connected with html page?

I have created a javascript page and connected it with html page. In the Javascript, i have created validation of the password and if there is a password mismatch then it will alert that there is a mismatch.
function validation()
{
if(password==repassword){
console.log(" ");
}
else{
alert(" ");
}
}
Above code is the javascript code and below is the html code.
LogIn
<label for="username">First Name: </label>
<input class="firstname" type="text" id="firstname" placeholder="First name"><br>
<label for="username">Last Name: </label>
<input class="lastname" type="text" id="lastname" placeholder="Last name"><br>
<label for="email">Email id: </label>
<input class="email" type="email" id="email" placeholder="Email id"><br>
<label for="labeltext">Password: </label>
<input class="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<label for="labeltext">Re-Password: </label>
<input class="Re-Password" type="password" id="repassword" placeholder="Re-Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<button class="Submit" onclick="validation()">Submit</button>
<button class="reset">Reset</button>
</form>
Does anyone know what's wrong in my code? Thank you!
You must create a reference for each element in javascript:
const password = document.getElementById('password');
const repassword = document.getElementById('repassword');
Now your variables are not local and you can use them in your function:
function validation()
{
if(password.value==repassword.value){
console.log(" ");
}
else{
alert(" ");
}
}
I believe what you want to do is to check if the password matches the verify password value.
From your javascript codes, everything looks good but if it is not working, then there is a problem with your HTML elements IDs i.e password field id and verify password field id. Check if you are making a mistake in any of the code you are using to get the element values.
A little mistake like
var x = document.getElementById("txtpass").value;
Where as, in your HTML source, there is no such element with txtpass as id could cause your javascript codes to break.
I would advise you post the complete HTML and Javascript codes.
Better still, use your browser console to check for the runtime error that is depriving your code from running as expected.
Use name=password in your password and name=repassword in your repassword tag like
<input class="password" name="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>

pattern() function and onkeyup() function not working together

i am trying to let the screen show that the password inserted should be in a certain regex with pattern when typing in the fields but when i used onkeyup() to check if both passwords are matching the part with the onkeyup works but
the pattern info box doesnt show up anymore
so i was hoping to know why its not working ,if both functions are not allowed together or anything
here is the html
<div class ="signupbox">
<h1>Signup</h1>
<form action="">
<p>Username</p>
<input type="text" id="user" placeholder="Enter Username" pattern="^[a-zA-Z0-9]{8,}$" title="please enter a username with only Letters and numbers[0-9]">
<p>Password</p>
<input name="password" id="password" type="password" placeholder="Enter Password" pattern="(?=.*[a-zA-Z].*)(?=.*[A-Z])(?=.*[0-9])(?=.*[##!%])[a-zA-Z0-9##!%]{6,}" title="please enter a password with at least 1 capital letter and one special from[##!%]" onkeyup='check();'/>
<p>confirm password</p>
<input type="password" name="confirm_password" id="confirm_password" placeholder="confirm Password" onkeyup='check();' />
<span id='message'></span>
<br>
<input type="submit" id="Signup" disabled value="Signup" >
</form>
here is the js
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'rgb(1, 126, 11)';
document.getElementById('message').style.fontSize="20px"
document.getElementById('message').innerHTML = "Passwords are matching";
} else {
document.getElementById('message').style.color = 'rgba(255, 0, 0, 0.829)';
document.getElementById('message').style.fontSize="20px"
document.getElementById('message').innerHTML = "Passwords are not matching";
sign.disabled=true;
}
}
Simply adding oninput="this.reportValidity()" to all input fields with a pattern, in addition to your onkeyup='check();', will show the browser-based validation feedback.

`Required` attribute not working with <form> tag [duplicate]

This question already has answers here:
HTML5 required attribute not working
(2 answers)
Closed last month.
My required attribute doesn't specify that an input field must be filled out before submitting the form.
HTML:
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password" placeholder="Enter Password" name="psw" onfocus="this.value=''"
required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword" placeholder="Confirm Password" name="psw-confirm" onfocus="this.value=''"
required>
<br>
<br>
<p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<button type="button" class="signupbtn" onclick="signUp()">Sign Up</button>
</div>
</div>
</form>
JavaScript:
function signUp() {
if (document.getElementById("password").value == document.getElementById("cfmpassword").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username = document.getElementById("username").value;
users.email = document.getElementById("email").value;
users.password = document.getElementById("password").value;
var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details
postUser.open("POST", "/users", true);
postUser.setRequestHeader("Content-Type", "application/json");
postUser.send(JSON.stringify(users));
//go to the logged in page
window.location = "main.html";
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
As the required attribute does not work, users can continuously submit empty forms and those will be stored in my SQL database
I don't have a <button type="submit"> in the form as this prevents me from using windows.location.
I am new to programming, can someone please give some suggestions (with explanations) on what to do to fix this? Any help would be appreciated! Thanks a lot! (I am using vanilla JavaScript for this)
The required attribute does not work because your form is not submitted. You need to specify a button with a type="submit" or <input type="submit"> to submit your form.
I suggest you to move the signUp function inside the form tag like this with an onsubmit event:
<form onsubmit="signUp(event)">.
Then add this to you Javascript function:
function signUp(event) {
event.preventDefault();
... your old code
}
For me, I see a number of possible issues. I have tried to remove them with the following sample code. I am assuming that /users will return something useful for checking and alerting the member if there is an error with the accessing of /users or the processing of the data.
The use of the required attribute of <input> will do nothing obvious in your code as the <button> has an onclick=signUp() call which will triggered before the browser check. With your current code the form values (present or not) will still be sent to /users as there is no testing for those values.
You need to move the signUp() call to the <form> if you want the browser check to be run.
To test this, removing the onclick=signUp() in the <button> will show you a browser tip window saying the value is needed.
As you are insisting on using AJAX to post the form data, moving the check to the <form> submit is idea and personally, I would still be checking the values - just good practice.
The next issue is you are not waiting for the return of a success or fail response from /users. In fact, you are blindly redirecting to main.html. If there is an error, the user will never know. This is a very bad user experience.
This is corrected in the sample code by checking for a response with a call-back, checking that response value and then alerting the member or redirecting if there is no error.
var users = {};
function ajaxPost(url,postData,callFunc) {
var http = new XMLHttpRequest();
if(! http){
return false;
}
http.onreadystatechange=function(){
if((http.readyState == 4) && (http.status == 200)) {
if(callFunc){
callFunc(http.responseText);
}
}
}
http.open('POST',url,true);
http.send(postData);
}
function validResult(str) {
if (str == "valid") {
// go to the logged in page
window.location = "main.html";
} else {
console.log("invalid result, let the user know");
}
}
function signUp(e) {
if(e){e.stopPropagation();e.preventDefault();}
var d = document.getElementById("signupForm").querySelectorAll("input");
var i, max = d.length;
// Quick check for values only. No check for the format of the values.
// This is good practice as a browser may still ignore the `required`
// attribute.
for(i=0;i<max;i++) {
d[i].value = d[i].value.trim();
if (d[i].value) {
users[d[i].name] = d[i].value;
} else {
// An alert would be better for the user here.
console.log("Missing value for ["+ d[i].name +"]");
// Go no further if there is a missing value.
return;
}
}
// at this point, all values added to the users object.
console.log("users:["+ JSON.stringify(users) +"]");
// Send the data and wait for a return value from /users
// --- remove comment on the following line to post ----
//ajaxPost("/users",JSON.stringify(users),validResult);
}
window.onload = function(){
var c = document.getElementById("signupForm");
if (c) {
c.addEventListener("submit",signUp,false);
}
}
<form id="signupForm">
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<p>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<p>
<button id="submit" type="submit">Check and submit</button>
</form>
Basic of HTML5 validation. You have it on button click and that runs before the validation happens. This shows you that the onclick runs and the onsubmit does not. Use the correct event.
function loginSubmit () {
console.log('loginSubmit')
}
function loginClick () {
console.log('loginClick')
}
<form onsubmit="loginSubmit()">
<input name="foo" required />
<button onclick="loginClick()">click</button>
</form>
The way required attribute works is it determines whether the element its assigned to has a value length higher than a zero, if that statement is false (meaning the value length of zero) then upon submitting the form it focuses that element as its "required" to be fulfilled.
Here is an example with JavaScript and how checking input fields could work inside it.
const form = document.querySelector('form[action="signup.php"]'); // Form
const inputs = form.querySelectorAll('input'); // All input elements inside the form
const submit = form.querySelector('button[type="submit"]'); // Submit button inside the form
// Add onclick event to the form button
submit.addEventListener('click', function(event) {
event.preventDefault(); // This prevents the button from submitting the form the traditional way
submit_form(); // but instead our way
});
function submit_form()
{
// We iterate through the form input elements
for (var i = 0; i < inputs.length; i++)
{
// We check if the current element has
// the attribute required and if so
// we proceed with checks
if (inputs[i].hasAttribute('required') && inputs[i].value.length == 0)
{
inputs[i].focus(); // We focus on the required element
alert(inputs[i].placeholder+' is required!'); // Alert the user that the element is required
break; // Break from the loop
}
else
{
if (i == (inputs.length - 1)) form.submit(); // If the loop's i variable counter hits the same value as the
// input elements length then it means all fields are filled
}
}
}
form {
width:300px;
margin:auto
}
form button,
form input {
width:100%;
height:48px;
padding:0 15px;
font-size:18px;
box-sizing:border-box;
}
form input:focus {
background-color:#f2dfb7;
}
<form action="signup.php" method="POST">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<input type="email" name="email_repeat" placeholder="Email Address (Repeat)" required>
<input type="password" name="password" placeholder="Password" required>
<input type="text" name="phone" placeholder="Phone Number" required>
<input type="text" name="birthday" placeholder="Birthday (MM/DD/YYYY)" required>
<button type="submit">Sign Up</button>
</form>

How to validate an input type="text" element to only accept certain content?

I have a text input field:
<input type="text" name="email" size="25" placeholder="Email Address" required/>
Is there a way to format the input field to only allow certain text to be valid?
For example: In that particular text field, the user must input an email address which ends in #hotmail.co.uk. Any other email domains such as #yahoo.com will not be valid and therefore will show an error when clicking submit (Will not register the user).
You can use the HTML5 pattern attribute to validate whether the string ends with #hotmail.co.uk.
In this case you can use the following regular expression:
^.*#hotmail\.co\.uk$
<form>
<input type="text" name="email" pattern="^.*#hotmail\.co\.uk$" size="25" placeholder="Email Address" required/>
<input type="submit" />
</form>
Alternatively, you could also just attach an input event listener to the element and check manually. This is just a basic example, feel free to customize to your needs. I would still suggest validating that the value is a valid email address by using the regex from this question.
$('input[name="email"]').on('input', function(e) {
var isValid = this.value.match(/^.*#hotmail\.co\.uk$/) !== null;
$(this).toggleClass('isValid', isValid);
});
.isValid {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="email" size="25" placeholder="Email Address" required/>
<input type="submit" />
</form>
many solutions are available:
validate form with javascript.
use 2 inputs: a text input for the username and a select options or radio buttons for "#site.com"
pattern attribute on input
Extended answer using the "pattern" attribute (from Josh Crozier):
After the user changed the value of the input you can check it for a valid input:
In addition you could test the input while the user is typing the value and highlight the border:
function check(el) {
if (new RegExp(el.pattern).test(el.value) == false) {
alert("Bad Input")
}
}
function test(el) {
if (new RegExp(el.pattern).test(el.value) == false) {
el.classList.add("bad")
} else {
el.classList.remove("bad")
}
}
.bad {
border-color: red;
}
<input pattern="^.*#hotmail\.co\.uk$" onchange="check(this)" oninput="test(this)" type="text" name="email" size="25" placeholder="Email Address" required/>

equalTo validation with jQuery Validate

Below is my form which has password and confirm password field
<div class="form-group">
<label class="control-label">password</label>
<input type="text" class="form-control" name="password"
data-validate="minlength[8]"
data-message-required="email is required" placeholder="password">
</div>
<div class="form-group">
<label class="control-label">confirm password</label>
<input type="text" class="form-control" name="password_confirm"
data-validate="minlength[8],equalTo[password]"
data-message-required="email is required" placeholder="confirm password">
</div>
Below is my part of validation field.
if (params = rule.match(/(\w+)\[(.*?)\]/i)) {
if ($.inArray(params[1], ['minlength', 'equalTo']) != -1) {
opts['rules'][name][params[1]] = params[2];
message = $field.data('message-' + params[1]);
if (message) {
opts['messages'][name][params[1]] = message;
}
}
}
The minlength[8] seems to work perfectly, but when i try to match my password with confirm password its not working. I tried passing the name attribute in three ways, but none of them work.
equalTo[password]
equalTo["password"]
equalTo["#password"]
Also can anyone tell me what does this regular expression do /(\w+)\[(.*?)\]/i)
The parameter inside equalTo["#password"] is #password.
#password is a jQuery selector that matches an element with id="password". However, I don't see a id attribute on your password field. Try adding one...
<input type="text" class="form-control" id="password" name="password" ....
Quote OP:
"Also can anyone tell me what does this regular expression do /(\w+)\[(.*?)\]/i"
See: http://regexr.com/39d43

Categories

Resources