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.
Related
So essentially my problem is that I am trying to make a form where certain rules need to be met, like the password should have an uppercase and you need to confirm your password, but despite failing the validation the form will still submit. The only validation that works is the default requirement that the text box needs to have something written in it. How would I go about making it so the validation actually stops the form from going through.
The code I currently have works in that it will return true/false depending on if it passes, its just that even if it does not pass the form will still go through. I know I probably need a event.preventDefault() somehwhere but I don't know where.
<form class="w3-container w3-margin" name="login" action="loginAction.jsp">
<h1>Create a Username and Password</h1>
<!-- These divs are the text fields for information the user needs to give the website -->
<div class="w3-section">
<label>Username</label>
<input class="w3-input w3-border" type="text" placeholder="Name" name="username" size="20" required>
</div>
<div class="w3-section">
<label>Email</label>
<input class="w3-input w3-border" type="text" placeholder="Email" name="email" required>
</div>
<!-- For the password the method validPassword() is used which checks if the password has an uppercase -->
<div class="w3-section">
<label>Password (Must have at least one upper case)</label>
<input class="w3-input w3-border" type="text" placeholder="Password" name="password" onInput="validPassword()" size="15" required>
</div>
<!-- For confirm password the method matchingPasswords() is used which checks if the two typed passwords are the same -->
<div class="w3-section">
<label>Confirm Password</label>
<input class="w3-input w3-border" type="text" placeholder="Confirm Password" name="cpassword" onInput="matchingPasswords()" size="15" required>
</div>
<!--These are submit and reset buttons -->
<div class="w3-section">
<input class="w3-button topbotColor" type="submit" value="Button" />
<input class="w3-button topbotColor" type="reset" value="Reset" />
</div>
</form>
This is the javascript code.
//function validPassword is meant to check if the password has a uppercase letter
function validPassword() {
//var password stores the password element from the text box
var password = document.getElementsByName("password");
//var ucletters is the set of all capital letters
var ucletters = /^(?=.*[A-Z]).+$/;
//If there is at least one uppercase in the password text
if(ucletters.test(password[0].value)){
//Pass validity and return true
document.getElementsByName("password").setCustomValidity("");
return true;
}
else {
//else the password does not have an uppercase
document.getElementByName.setCustomValidity("This password does not fit criteria");
return false;
}
}
//matchingPasswords is meant to check if two passwords were the same
function matchingPasswords() {
//password stores the text in the password text box
var password = document.getElementsByName("password");
//cpassword stores the text in the confirm password text box
var cpassword = document.getElementsByName("cpassword");
//If the string in password does not match the string in confirm password
if (password[0].value !== cpassword[0].value) {
//it fails validity and should return false
document.getElementsByName("cpassword").setCustomValidity("Emails do not match");
return false;
}
else {
//else it passes and should be true
document.getElementsByName("cpassword").setCustomValidity("");
return true;
}
}
/*function completeForm() {
if (validPassword() !== true && matchingPasswords() !== true){
event.preventDefault();
}
}*/
1.) Remove the forms action value
2.) Add Event Listeners for your code to run(I don't see how any functions are running)
document.getElementById("your_submit_button").addEventListener('click', function_you_want_to_run);
3.) Use this code to redirect the client to your form action
window.location.url="/link.jsp";
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>
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)
Is there a way to require the entries in two form fields to match using HTML? Or does this still have to be done with JavaScript? For example, if you have two password fields and want to make sure that a user has entered the same data in each field, are there some attributes, or other coding that can be done, to achieve this?
Not exactly with HTML validation but a little JavaScript can resolve the issue, follow the example below:
function check() {
var input = document.getElementById('password_confirm');
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
<p>
<label for="password">Password:</label>
<input name="password" required="required" type="password" id="password" oninput="check()"/>
</p>
<p>
<label for="password_confirm">Confirm Password:</label>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check()"/>
</p>
<input type="submit" />
You can with regular expressions Input Patterns (check browser compatibility)
<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>
<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>
A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.
Unfortunately, you also need to escape the regex, for which no standard function exists.
<form>
<input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
<input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
</script>
JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output> element and an oninput form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
Not only HTML but a bit of JavaScript
HTML
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
JavaScript
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
confirm_password.setCustomValidity( password.value !=
confirm_password.value ? "Passwords Don't Match" : '');
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
CodePen Demo
As has been mentioned in other answers, there is no pure HTML way to do this.
If you are already using JQuery, then this should do what you need:
$(document).ready(function() {
$('#ourForm').submit(function(e){
var form = this;
e.preventDefault();
// Check Passwords are the same
if( $('#pass1').val()==$('#pass2').val() ) {
// Submit Form
alert('Passwords Match, submitting form');
form.submit();
} else {
// Complain bitterly
alert('Password Mismatch');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ourForm">
<input type="password" name="password" id="pass1" placeholder="Password" required>
<input type="password" name="password" id="pass2" placeholder="Repeat Password" required>
<input type="submit" value="Go">
</form>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
value={password}
onChange={(e) => { setPassword(e.target.value) }}
type="password" id='password' name="password" required minLength={3} maxLength={255} />
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
title='Passwords should be match'
pattern={`${password}`}
value={confirmPassword}
onChange={(e) => { setConfirmPassword(e.target.value) }}
type="password" id='confirmPassword' name="confirmPassword" required minLength={3} maxLength={255} />
</div>
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