issue with setCustomValidity - javascript

I am writing a simple if statement to test whether the passwords in each input boxes match. If they both match, no error is given and if they do not match the error "they do not match" is given using .setCustomValidity(). The issue I am having is when the error is given and then the passwords are corrected to match, the error is still given. I'm not sure what i'm doing wrong. Below is my code and a link to a working JSfiddle.
JSfiddle: https://jsfiddle.net/1934foej/
HTML:
<label>
<input id="first" type="text" min="16" max="100" placeholder="New password" autofocus required>
</label>
<label>
<input id="second" type="text" min="16" max="100" placeholder="Repeat password" required>
</label>
<input id="submit" type="submit">
JS:
var firstPasswordInput = document.querySelector('#first');
var secondPasswordInput = document.querySelector('#second');
var submit = document.querySelector('#submit');
submit.onclick = function () {
var firstPassword = firstPasswordInput;
var secondPassword = secondPasswordInput;
//checks for match
if( firstPassword.value !== secondPassword.value) {
firstPasswordInput.setCustomValidity("they do not match");
}
}

The error you are doing is the customValidity remains "they do not match" because you are not setting it to empty string (which the browser takes it as successful validation), so the input remains with the same state after one unsuccessful validation.
submit.onclick = function() {
// there is no need to redefine these two variables
var firstPassword = firstPasswordInput;
var secondPassword = secondPasswordInput;
if(firstPassword.value !== secondPassword.value) {
firstPassword.setCustomValidity("they do not match");
}
//add this part
else {
firstPassword.setCustomValidity("");
}
}

Related

if contact number is both empty and does not have 11 digits

id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

Validate form if a condition is met

I am working on a credit card project. And I have a function in javascript (validateCreditCard) that helps me validate the credit card and return the credit card type. After getting the credit card type, I store as value of the hidden input cardType to be used after submission of the form. after clicking on the submit button, the user is taken to 'proceed.php' if the function cardFormValidate returns true.
This is what I have being trying to realize by writing those lines of code but the value of the hidden input is still empty. Kindly help me.
Sorry I am not a native english speaker
function cardFormValidate() {
//Card validation
var card_number = $('#CreditCardNumber');
card_number.validateCreditCard(function (result) {
var cardType = (result.card_type == null) ? '' : result.card_type.name;
if (result.valid) {
$("#cardType").val(cardType);
cardValid = true;
} else {
$("#cardType").val('');
cardValid = false;
}
return cardValid;
});
}
$(document).ready(function() {
//Submit card form
$("#PayButton").on('click',function(){
if (cardFormValidate()) {
//Move to proceed.php to treat the form
}else{
alert('bad credit card');
}
});
});
<form method="post" action="proceed.php">
<input name="cardType" type="hidden" id="cardType">
<div class="form-group">
<label for="NameOnCard">Name on card</label>
<label for="NameOnCard"></label><input id="NameOnCard" class="form-control" type="text" name="NameOnCard" maxlength="255"/>
</div>
<div class="form-group">
<label for="CreditCardNumber">Card number</label>
<input id="CreditCardNumber" class="null card-image form-control" name="CreditCardNumber" type="text"/>
</div>
<button id="PayButton" type="submit"></button>
</form>
I think validateCreditCard function is not executing properly and you are getting null value ..
1 ) first check Are You getting Card_Number??
put alert(card_number) if not then
try this line
var card_number = $('#CreditCardNumber').val();
2) return data of validateCreditCard must have name property check it out otherwise you will get null value..

Validate Form - Multiple Error Messages Appearing

I am trying to write a pure JavaScript form validation that will add an error message next to the label elements if the input is empty.
The confirmEmail input gets an additional error message if it does not match the email input
My problem is that if you hit the submit button when all fields are empty, then put a value into the email input but leave confirmEmail empty and hit submit again, both error messages will appear next to the confirmEmail's label. The ideal result would be that confirmEmail only has text that says "Email does not match"
Here is a fiddle: http://jsfiddle.net/R5e2T/
Here is my HTML:
<div id="theForm">
<div>
<label for="firstName">First Name:</label>
<br>
<input type="text" id="firstName" name="first" value="" />
</div>
<div>
<label for="lastName">Last Name:</label>
<br>
<input type="text" id="lastName" name="last" value="" />
</div>
<div>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email" value="" />
</div>
<div>
<label for="confirmEmail">Confirm Email:</label>
<br>
<input type="text" id="confirmEmail" name="confirmEmail" value="" />
</div>
<button type="button" id="submitButton">Submit</button>
</div>
Here is my JavaScript:
function validate () {
var theForm = document.getElementById('theForm'),
firstName = document.getElementById('firstName'),
lastName = document.getElementById('lastName'),
email = document.getElementById('email'),
confirmEmail = document.getElementById('confirmEmail'),
label = theForm.getElementsByTagName('label'),
input = theForm.getElementsByTagName('input'),
inputLength = input.length;
// Remove any spans that may have been added by the next for loop
for (var x = 0; x < inputLength; x++) {
var currLbl = label[x];
if ( currLbl.parentNode.getElementsByTagName('span').length > 0 ) {
var span = currLbl.parentNode.getElementsByTagName('span')[0];
removeElement(span);
}
}
// Error checking for the form.
// Add error message next to any element that has a blank value.
for (var i = 0; i < inputLength; i++) {
// innerText for IE, textContent for other browsers
var labelText = label[i].innerText || label[i].textContent;
var currLabel = label[i];
var text = document.createTextNode( labelText + ' cannot be empty');
if ( input[i].value === '' ) {
currLabel.parentNode.style.color = 'red';
currLabel.insertAdjacentHTML('afterend', ' <span>cannot be empty</span>');
}
else if ( input[i].value !== '') {
currLabel.parentNode.style.color = '';
}
}
// Test to see if confirmEmail is equal to email.
// If not add a warning message next to confirmEmail's label
if (confirmEmail.value !== email.value) {
var labelElement = confirmEmail.parentNode.getElementsByTagName('label')[0]
labelElement.insertAdjacentHTML('afterend', ' <span>Email does not match</span>');
labelElement.parentNode.style.color = 'red';
}
// Test to make sure all inputs have a value,
// and that confirmEmail equals email.
if (firstName.value !== '' && lastName.value !== '' && email.value !== '' && confirmEmail.value !== '' && email.value === confirmEmail.value) {
alert("Submitted!!!");
return true;
} else {
return false;
}
};
// Remove Element function
function removeElement(node) {
node.parentNode.removeChild(node);
}
(function () {
var button = document.getElementById('submitButton');
button.addEventListener('click', validate, false);
}());
I forked your fiddle.
What I did was to use innerHtml and just replace the text of the label, instead of creating new span-nodes and appending them to the document.
I store the original label, like "E-Mail" in a dataset variable, so that I can reset the label later.
Another solution is to add this before you add the "Email doensn't match" message:
var oldSpan = labelElement.parentNode.getElementsByTagName('span')[0];
removeElement(oldSpan);
An even better solution would be to check for confirmEmail matching email before checking for empty fields and do not add the "cannot be empty" message if another error message has been added already.

how to correctly validate a form using javascript .?

I am trying to validate a form using javascript, Here is my code
<script type="text/javascript">
function prevSubmit(){
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var flag = 1;
if (pass1.value.length>16) {
document.getElementById("passError").innerHTML = "password may atleast 16 chars";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
if(pass1.value<=16 && pass1.value!=pass2.value)
{
document.getElementById("passError").innerHTML = "password must be same";
flag = 0;
}
else
document.getElementById("passError").innerHTML = "";
return flag;
}
</script>
and here is my form element,
<form id="registration_form" action="registration.php" method="post" onsubmit="return prevSubmit();">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span id="NameError"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span id="emailError"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span id="passError"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
what I am trying to accomplish is check the password, if no match or greater than 16, then show the message and prevent submission, but its not working, Why?
Use true and false as the values of flag, not 1 and 0. You have to return false to prevent submission, anything else allows submission.
First this error message makes no sense
password may atleast 16 chars
Secondly, your second error check is wrong
if(pass1.value<=16 && pass1.value!=pass2.value)
You are saying if the value is less that the number 16 and the two values do not match.
Why would the value be less that 16? The check should just be
if (pass1.value!=pass2.value)
ANd as the others suggested, use true/false, not 1 and 0 as truthy values.
I agree with answers of Barmar and epascarello.
The if conditions should be implemented in this way:
var oForm = document.forms[0];
var pass1= oForm.elements["passwd"];
var pass2=oForm.elements["repasswd"];
var ctrlError = document.getElementById("passError");
if (pass1.value.length < 16) {
ctrlError.innerHTML = "Password must be at least 16 characters long.";
return false;
}
else if (pass1.value != pass2.value) {
ctrlError.innerHTML = "Passwords do not match.";
return false;
}
else {
ctrlError.innerHTML = "";
return true;
}
just "return false" from javascript method
<input type="submit" class="button" value="sign up" onclick="javascript:return myFunc();"/>
function myFunc()
{
return false;
}
this is basic example of how to prevent submission of form, if we return false then browser/javascript engine prevent further propagation of click event and submission is prevented.

Categories