how to check confirm password field in form without reloading page - javascript

I have a project in which I have to add a registration form and I want to to validate that the password and confirm fields are equal without clicking the register button.
If password and confirm password field will not match, then I also want to put an error message at side of confirm password field and disable registration button.
following is my html code..
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" /></label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
</label>
<label>
<input type="submit" name="submit" value="registration" />
</label>
Is there any way to do this?

We will be looking at two approaches to achieve this. With and without using jQuery.
1. Using jQuery
You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password field changes. Thanks #kdjernigan for pointing that out
In this way, when you type in the field you will know if the password is same or not:
$('#password, #confirm_password').on('keyup', function () {
if ($('#password').val() == $('#confirm_password').val()) {
$('#message').html('Matching').css('color', 'green');
} else
$('#message').html('Not Matching').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
<input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
<span id='message'></span>
</label>
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/
2. Without using jQuery
We will use the onkeyup event of javascript on both the fields to achieve the same effect.
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
}
}
<label>password :
<input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onkeyup='check();' />
<span id='message'></span>
</label>
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/

Using Native setCustomValidity
Compare the password/confirm-password input values on their change event and setCustomValidity accordingly:
function onChange() {
const password = document.querySelector('input[name=password]');
const confirm = document.querySelector('input[name=confirm]');
if (confirm.value === password.value) {
confirm.setCustomValidity('');
} else {
confirm.setCustomValidity('Passwords do not match');
}
}
<form>
<label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />
<label>Confirm : <input name="confirm" type="password" onChange="onChange()" /> </label><br />
<input type="submit" />
</form>

If you don't want use jQuery:
function check_pass() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
}
<input type="password" name="password" id="password" onchange='check_pass();'/>
<input type="password" name="confirm_password" id="confirm_password" onchange='check_pass();'/>
<input type="submit" name="submit" value="registration" id="submit" disabled/>

Solution Using jQuery
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<style>
#form label{float:left; width:140px;}
#error_msg{color:red; font-weight:bold;}
</style>
<script>
$(document).ready(function(){
var $submitBtn = $("#form input[type='submit']");
var $passwordBox = $("#password");
var $confirmBox = $("#confirm_password");
var $errorMsg = $('<span id="error_msg">Passwords do not match.</span>');
// This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
$submitBtn.removeAttr("disabled");
function checkMatchingPasswords(){
if($confirmBox.val() != "" && $passwordBox.val != ""){
if( $confirmBox.val() != $passwordBox.val() ){
$submitBtn.attr("disabled", "disabled");
$errorMsg.insertAfter($confirmBox);
}
}
}
function resetPasswordError(){
$submitBtn.removeAttr("disabled");
var $errorCont = $("#error_msg");
if($errorCont.length > 0){
$errorCont.remove();
}
}
$("#confirm_password, #password")
.on("keydown", function(e){
/* only check when the tab or enter keys are pressed
* to prevent the method from being called needlessly */
if(e.keyCode == 13 || e.keyCode == 9) {
checkMatchingPasswords();
}
})
.on("blur", function(){
// also check when the element looses focus (clicks somewhere else)
checkMatchingPasswords();
})
.on("focus", function(){
// reset the error message when they go to make a change
resetPasswordError();
})
});
</script>
And update your form accordingly:
<form id="form" name="form" method="post" action="registration.php">
<label for="username">Username : </label>
<input name="username" id="username" type="text" /></label><br/>
<label for="password">Password :</label>
<input name="password" id="password" type="password" /><br/>
<label for="confirm_password">Confirm Password:</label>
<input type="password" name="confirm_password" id="confirm_password" /><br/>
<input type="submit" name="submit" value="registration" />
</form>
This will do precisely what you asked for:
validate that the password and confirm fields are equal without clicking the register button
If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button
It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.
Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.

function check() {
if(document.getElementById('password').value ===
document.getElementById('confirm_password').value) {
document.getElementById('message').innerHTML = "match";
} else {
document.getElementById('message').innerHTML = "no match";
}
}
<label>password :
<input name="password" id="password" type="password" />
</label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onchange="check()"/>
<span id='message'></span>

HTML CODE
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
JS CODE
function checkPass(){
var pass = document.getElementById("password").value;
var rpass = document.getElementById("rpassword").value;
if(pass != rpass){
document.getElementById("submit").disabled = true;
$('.missmatch').html("Entered Password is not matching!! Try Again");
}else{
$('.missmatch').html("");
document.getElementById("submit").disabled = false;
}
}

try using jquery like this
$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});
also add this line in head of html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

$('input[type=submit]').on('click', validate);
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("valid");
}
else {
$("#validate-status").text("invalid");
}
}
Logic is to check on keyup if the value in both fields match or not.
Working fiddle: http://jsfiddle.net/dbwMY/
More details here: Checking password match while typing

<form id="form" name="form" method="post" action="registration.php" onsubmit="return check()">
....
</form>
<script>
$("#form").submit(function(){
if($("#password").val()!=$("#confirm_password").val())
{
alert("password should be same");
return false;
}
})
</script>
hope it may help you

Try this one ;
CSS
#indicator{
width:20px;
height:20px;
display:block;
border-radius:10px;
}
.green{
background-color:green;
display:block;
}
.red{
background-color:red;
display:block;
}
HTML
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" id="password" /></label> <br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" /><span id="indicator"></span> <br>
</label>
<label>
<input type="submit" name="submit" id="regbtn" value="registration" />
</label>
</form>
JQuery
$('#confirm_password').keyup(function(){
var pass = $('#password').val();
var cpass = $('#confirm_password').val();
if(pass!=cpass){
$('#indicator').attr({class:'red'});
$('#regbtn').attr({disabled:true});
}
else{
$('#indicator').attr({class:'green'});
$('#regbtn').attr({disabled:false});
}
});

WITHOUT clicking the button you will have to listen to the change event of the input fields
var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");
function checkPasswordMatch(){
var status = document.getElementById("password_status");
var submit = document.getElementById("submit");
status.innerHTML = "";
submit.removeAttribute("disabled");
if(confirmField.value === "")
return;
if(passwordField.value === confirmField.value)
return;
status.innerHTML = "Passwords don't match";
submit.setAttribute("disabled", "disabled");
}
passWordField.addEventListener("change", function(event){
checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
checkPasswordMatch();
});
then add the status element to your html:
<p id="password_status"></p>
and set the submit button id to submit
... id="submit" />
hope this helps you

$box = $('input[name=showPassword]');
$box.focus(function(){
if ($(this).is(':checked')) {
$('input[name=pswd]').attr('type', 'password');
} else {
$('input[name=pswd]').attr('type', 'text');
}
})

You can check confirm password by only simple javascript
html
<input type="password" name="password" required>
<input type="password" name="confirmpassword" onkeypress="register()" required>
<div id="checkconfirm"></div>
and in javascript
function register() {
var password= document.getElementById('password').value ;
var confirm= document.getElementById('confirmpassword').value;
if (confirm!=password){
var field = document.getElementById("checkconfirm")
field.innerHTML = "not match";
}
}
Also you can use onkeyup instead of onkeypress.

The code proposed by #Chandrahasa Rai
works almost perfectly good, with one exception!
When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234". You have to give it a chance by letting key go up :)
Now everything should be working fine!
#Chandrahasa Rai,
HTML code:
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
#my modification:
<input type="text" onkeyup="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeyup="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

I think this example is good to check https://codepen.io/diegoleme/pen/surIK
I can quote code here
<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>
and
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

Related

How Do I Add An Error Message To An Incorrect Input With JS? [duplicate]

This question already has answers here:
how to check confirm password field in form without reloading page
(15 answers)
Closed 10 months ago.
I am trying to add some error messages to my inputs through JS, but I am not exactly sure how I should go about this, and everything I've tried does not function well.
I am trying to display an error, and prevent the form from submitting, if there is an error.
<form novalidate>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" />
<span id='pwmessage'></span>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" />
<span id='cpwmessage'></span>
</label>
<button>Submit</button>
</form>
Just try this one! In here, the form won't be submitted if the password or confirm password is missing or the confirm password is not same as the first password.
function empty() {
if (document.getElementById("password").value == "") {
document.getElementById("pwmessage").innerHTML = "Enter at least one character to the password field";
return false;
}
if (document.getElementById("confirm_password").value != document.getElementById("password").value) {
document.getElementById("cpwmessage").innerHTML = "Please check your password and try again";
return false;
};
}
<form novalidate action='process.php' method='get'>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" /><br>
<span id='pwmessage'></span><br>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" /><br>
<span id='cpwmessage'></span><br>
</label>
<input type="submit" value="submit" onClick="return empty()" />
</form>
Thanks and best regards!
There are plenty of form validation tutorials out there to give you further inspiration.
This version makes use of data attributes and is very scalable without the need for more javascript. More work will be needed for additional input types but should be enough to get you started.
//Set valudation on blur for each of the elements
document.querySelectorAll("[data-customvalidate] input").forEach(function(element) {
element.addEventListener("blur", function() {
validateField(this)
});
});
//Set form validation
document.querySelectorAll("[data-customvalidate").forEach(function(element) {
element.addEventListener("submit", function(event) {
let isNotValid = false;
//Go through each of the input element
this.querySelectorAll("input").forEach(function(input) {
//Validate the input and set the isNotValid flg
if (validateField(input) && !isNotValid) {
isNotValid = true;
}
});
//Stop the form submit if not valid
if (isNotValid) {
event.preventDefault();
}
});
});
//Main Validation Funtion
function validateField(field) {
let attributes = field.getAttributeNames();
let parent = field.parentNode
let errorField = parent.querySelector(".formError");
let isError = false;
//Required Vlidation
if (attributes.includes("required") && field.value === "") {
errorField.textContent = `The ${field.dataset.errorfieldname} field is required`;
isError = true;
//Min Length Validation
} else if (attributes.includes("minlength") && (field.value.length < field.getAttribute("minlength"))) {
errorField.textContent = `The mininmum length for ${field.dataset.errorfieldname} field is ${field.getAttribute("minlength")} characters`;
isError = true;
//Match Validation
} else if (attributes.includes("data-mustmatch")) {
let elementToMatch = document.getElementById(field.dataset.mustmatch);
if (elementToMatch.value !== field.value) {
errorField.textContent = `The ${elementToMatch.dataset.errorfieldname} and ${field.dataset.errorfieldname} do not match`;
isError = true;
}
}
parent.classList.toggle("error", isError);
return isError;
}
label {
display: block;
}
label:not(.error)>.formError {
display: none;
}
label>.formError {
color: red;
font-weight: bold;
padding-left: 1em;
}
<form novalidate data-customvalidate>
<label for="password">
<input type="password" name="password" id="password" placeholder="Password*" required minlength="8" data-errorfieldname="Password" />
<span class="formError"></span>
</label>
<label for="confirmpassword">
<input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" data-errorfieldname="Confirm Password" data-mustmatch="password" data-mustmatcherror= "Password and Confirm Password do not match" />
<span class="formError"></span>
</label>
<button>Submit</button>
</form>

How to disable submit button until all input classes have class="valid"

I want to create a sign-up form. I have 6 inputs: First Name, Last Name, E-mail, Password, Password confirmation and a checkbox for user agreement. If inputs have class="valid", value is valid, otherwise invalid. I put all the classes a default class="invalid". I want to disable my submit button until all input fields have class="valid". According to my research, I saw that the button should be disabled first using the window.onload eventlistener, but I still couldn't figure out how to do it.
This is the basic form:
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
I am controlling checkbox validation with an eventlistener:
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
})
And for the rest, i am checking with regexs:
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value])
})
})
Something like this might come in handy.
var form = document.querySelector('.signup__form'), is_valid = false, fields, button;
form.addEventListener('change', function(){
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if( fields[i].classList.contains('invalid') )
{
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled'): button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Since you don't have all of your code, I'm adding a second example myself so that I can fully test the validation part.
But you just need to copy the above JavaScript code and set the button to disabled="disabled"in the first place.
var form = document.querySelector('.signup__form'),
is_valid = false,
fields, button;
form.addEventListener('change', function() {
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if (fields[i].value.length) {
fields[i].classList.remove('invalid');
} else {
fields[i].classList.add('invalid');
}
if (fields[i].classList.contains('invalid')) {
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled') : button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name" /> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Note: This example does not follow because it does not validate the Checkbox.
#Enes, 1. kod parçacığındaki JavaScript kodunu kopyalarsan çalışacaktır. 2. Kodu test edebilmen için ekledim. Bir değer girilmişse onu doğru "valid" kabul eder.
I would try to the native use of HTML properties (pattern & required) and CSS instead of giving in to javascript. Just give it a go, and see how it feels like. Do note that I excluded a pattern on your email input.
The only thing I would use javascript for is to check if the password fields are the same, but I would do that by injecting the password of the first password input into the confirming password input's pattern attribute, replacing ^[\w#-]{8,20}$.
The pink background is just there to show-case the validation rules.
By the way, you got the wrong formatting on some of the HTML tags. You don't need an ending slash on input and you should type <br/>, not </br>.
input:invalid {
background-color: pink;
}
form:invalid button[type="submit"] {
opacity: 0.5;
}
<form class="signup__form" action="/">
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Name"> <br/>
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Last Name"><br/>
<input type="email" required placeholder="E-mail"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password Confirm"><br/>
<input type="checkbox" required>User Agreement<br/>
<button type="submit" >Sign Up</button>
</form>
you can use required="required", then the submit won't be called before the field has value.
A solution which tests the number of invalid classes:
var checkbox = document.querySelector("input[type=checkbox]");
var inputs = document.querySelectorAll("input:not([type='checkbox'])");
var but = document.querySelector("button[type=submit]");
but.disabled= true;
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value]);
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
})
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
We will use couple of properties to validate the form which are required, pattern, disabled and also we will use CSS properties to control the form validation
input:invalid {
background-color: red;
}
form:invalid input[type="submit"] {
opacity: 0.5;
cursor: not-allowed;
}
<form class="login__form" action="/">
<input type="email" required placeholder="E-mail"><br/><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/><br/>
<input type="submit" >
</form>

Validation not working perfectly

This is my code:
function email() {
var reg = new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam = document.registration.email.value;
var res = nam.match(reg);
if (res) {
alert("enter valid email");
document.registration.email.focus();
} else {
document.registration.password.focus();
}
} else {
document.registration.email.focus();
}
}
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" onblur="email()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
The validation is not working and thus the alert in if condition is not showing. Can anyone help me to achieve this type of validation.
Thanks in advance
Well... Assuming you are trying to do some input validation for your form I suggest reading a bit regarding email validation regex. Then use something like:
https://www.regextester.com/19
Then I think your if statement is flawed. I think you meant that if the email matchs the regular expression if should focus on the password field. if the email is not empty and is invalid if should present an alert. if the email is empty it should focus on the email. I did a quick cleanup and i think the code should look something like(untested code for illustration only):
function validateInput() {
var email= new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var inputValue=document.registration.email.value;
if(inputValue.match(email)) {
document.registration.password.focus();
} else if (inputValue.length > 0) {
alert("enter valid email");
document.registration.email.focus();
} else {
document.registration.email.focus();
}
}
email is a reserved keyword in javascript. first rename your function email to test or whatever you want. second thing you have extra else in your code.
There is a couple errors in your javascript - syntax and dom api.
If you want to do manual validation, here is an example in a fiddle that would work.
https://jsfiddle.net/xb4qrvmy/
function validate_email()
{
var reg=new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam=document.forms["registration"].email.value;
var res=nam.match(reg);
if(!res && nam.length)
{
// I would advice against using alert.
alert("enter valid email");
document.registration.email.focus();
// You want to somehow reset the displaying of the error.
document.forms["registration"].email.value = ''
} else if (res) {
document.registration.password.focus();
}
}
Since You are using html 5 you don't need to write your own validation for email just use
HTML5 has inbuilt validation check for email.
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="email" name="email" placeholder="Email" onblur="email()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
But in case you want to use your function anyways use it as :
<html>
<head>
<script>
function emails()
{
var reg=new RegExp("^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$");
var nam=document.registration.email.value;
if(!new RegExp(reg).test(nam))
{
alert(document.registration.email);
document.registration.password.focus();
} else {
document.registration.password.focus();
}
}
</script>
</head>
<body>
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" onblur="javascript:emails()" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
</body>
function validate()
{
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) {
alert("Not a valid e-mail address");
return false;
}
}
</script>

Disable an input with javascript. Checking the code

I'm doing a client side in javascript and html. I have a problem. I want to check if password and repeat password are the same. In that case I want to disable an input. I saw some codes around but I don't understand why it doesn't work. Can you help me?
Here is my HTML:
<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password">
<input class="btn btn-beats btn-block btn-stacked" value="Sign up" onkeydown="enable()" id = "btnPlaceOrder" type="submit">
<input class="form-control form-stacked" name="password" id = "password" placeholder="Password" type="password" required="true">
And then here is my javascript function:
var password = document.getElementById("password");
var repeat = document.getElementById("repeat");
function enable(){
if (password.value() == repeat.value()){
document.getElementById("btnPlaceOrder").disabled = false;
} else{
document.getElementById("btnPlaceOrder").disabled = true;
}
}
Just to be precise, I did the import of the javascript in my HTML
HTML:
Add listeners to the password inputs, so the submit button fill change its state as the user types.
<input id="password" type="password" onkeyup="enable()">
<input id="repeat" type="password" onkeyup="enable()">
<input value="Sign up" id="btnPlaceOrder" type="submit">
JS
function enable(){
// the comparison returns true or false so no need for if/else
document.getElementById("btnPlaceOrder").disabled = password.value !== repeat.value;
}
Fiddle: http://jsfiddle.net/40vvL1em/
Well simply call your function in the onkeyup() event of your repeat input.
<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password" onkeyup="enable()">
And here's the JS function:
var password = document.getElementById("password").value;
var repeat = document.getElementById("repeat").value;
function enable(){
if (password === repeat){
document.getElementById("btnPlaceOrder").disabled = false;
}
else{
document.getElementById("btnPlaceOrder").disabled = true;
}
}
That should do it.

Multiple Validation checks - logic error

I am providing a validation feature on a form for passwords. I need to be able to implement a few validation rules and have them all checked on submit. Now to me the code is sound but I think they may be some logic error in my code that I'm too tired to notice (too the coffee machine!)
Here's the JavaScript:
<script type="text/javascript">
<!--
function validate(registerForm)
registerForm.onsubmit=function()
{
var pw1 = document.forms["register"]["password1"].value;
var pw2 = document.forms["register"]["password2"].value;
//Check values are present in both fields
if(pw1 == '' || pw2 == '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 != pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
//Accept passwords
{
alert("Password accepted!");
return true;
}
}
}
-->
</script>
And the HTML Form to go with it:
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" value="Register" />
</form>
<script type="text/javascript">
<!--
new validate(document.forms['register']);
-->
</script>
Any ideas of lovely StackOverflow community? The exact problem is that it won't check for spaces in passwords or whether two passwords entered are the same. It successfully checks that there is at least something in both password fields.
Thanks Dan
This line:
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
invalid is not defined and I suspect this will cause the problems you're facing.
Made changes to your code got it working http://jsbin.com/igonec/edit#preview
ERRORS
Use of var pw1 = document.forms["register"]["password1"]. It was causing errors
Missing else.
Use of invalid instead of " ".
Wrong use of brackets.
I omitted your errors and made the solution more elegant.
Javascipt
function validate()
{
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
//Check values are present in both fields
if(pw1 ==='' || pw2 === '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.getElementById("password1").value.indexOf(" ") > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 !== pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
else
{
alert("Password accepted!");
return true;
}
}
}
HTML
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" onclick="validate()" value="Register" />
</form>

Categories

Resources