I'm trying to validate a password using javascript, It's to make sure that when changing the password, the new password entered is equal to that of the re-entering of the new password (user is asked to enter their new password twice so both have to match) but at the same time, i want to make sure that the new password is at least 6 characters long, I have these functions separately but don't know how to combine them... thanks for help in advance!
This is what i have so far...
This is to make sure the new passwords match:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
<!-- if they match, go to next page -->
if ( new_password == confirm_new_password)
{
return true;
}
<!-- if they don't match, an error message is displayed -->
else
{
alert("Passwords do not match.");
}
return false;
}
This is for length of password:
function validatePassword()
{
if (document.getElementById("new_password").value.length < "5")
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
return true;
}
How do i combine both of these to form a SINGLE function where the two new passwords are checked so that they match, and also check that they are longer than 6 characters?
To just combine your two functions, this would work:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (new_password.length < 5)
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
else if ( new_password != confirm_new_password)
{
alert("Passwords do not match.");
return false;
}
else
{
return true;
}
}
Although I agree, there are better procedures out there. And please, make sure you're doing server-side validation as well since client-side validation is very easy to skip around.
i m not sure but you can call validatePassword() this function inside
if ( new_password == confirm_new_password)
{
validatePassword();
}
You have two options, either make the two functions a single function, or make them two separate functions and call them both before you submit / process your form.
if (validatePasswordLength() && validatePasswordsMatch()) {
// Continue
}
you have to try this code that is small and working.
if(document.getElementById("new_password").value != document.getElementById("confirm_new_password").value){
alert("Passwords do not match.");
return false;
}
<script>
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (document.getElementById("new_password").value.length < "5")
{
alert("Please ensure your password is at least 6 characters long.");
return false;
}
if (new_password == confirm_new_password)
{
alert("Password no match");
return false;
}
return true;
}
</script>
<form action="" onsubmit="return validatePassword()">
<p>New Password: <input type="password" id="new_password" name="new_password" /></p>
<p>Confirm Password: <input type="password" id="confirm_new_password" name="confirm_new_password" /></p>
<p><input type="submit" value="submit" /></p>
</form>
Related
I made a HTML form and assigned two inputs into it, One for username and one for mobile number. I then made a function in Java Script and made two variables a and b for username and mobile number but on submitting the form the function seem to work only for one of the inputs , can someone provide a solution to this ?
I am expecting the messages assigned for username and mobile number to appear in the span tag on submittion of the form
i am providing the HTML and Java Script code below
<form onSubmit="return valid()">
HOME
<p><input type="text" id="user_name" value=""><span id="msg"></span></p>
Mobile
<p><input type="text" id="mobile" value=""><span id="msg"></span></p>
<p><input type="submit" value="submit"></p>
JavaScript Document
function valid()
{
var correct_way = /^[A-Za-z]+$/;
var a=document.getElementById("user_name").value;
if(a=="")
{
document.getElementById("msg").innerHTML=" please insert value";
return false;
}
if(a.length<3)
{
document.getElementById("msg").innerHTML=" username cannot be less than 3 charachters";
return false;
}
if(a.length>15)
{
document.getElementById("msg").innerHTML=" username cannot be greater than 15 charachters";
return false;
}
if(a==correct_way)
{
true;
}
else
{
document.getElementById("msg").innerHTML=" username should be only charachter";
return false;
}
var b=document.getElementById("mobile").value;
if(b=="")
{
document.getElementById("msg").innerHTML=" please enter mobile number";
return false;
}
if(isNaN(b))
{
document.getElementById("msg").innerHTML=" only numbers are allowed";
return false;
}
if(b.length<10)
{
document.getElementById("msg").innerHTML=" mobile number must be 10 digit";
return false;
}
if(b.length>10)
{
document.getElementById("msg").innerHTML=" mobile number must be 10 digit";
return false;
}
}
function valid()
{
var correct_way = /^[A-Za-z]+$/;
var a=document.getElementById("user_name").value;
if(a=="")
{
document.getElementById("user_name").nextSibling.innerHTML=" please insert value";
return false;
}
if(a.length<3)
{
document.getElementById("user_name").nextSibling.innerHTML=" username cannot be less than 3 charachters";
return false;
}
if(a.length>15)
{
document.getElementById("user_name").nextSibling.innerHTML=" username cannot be greater than 15 charachters";
return false;
}
if(!correct_way.test(a)){
document.getElementById("user_name").nextSibling.innerHTML=" username should be only charachter";
return false;
}
var b=document.getElementById("mobile").value;
if(b=="")
{
document.getElementById("mobile").nextSibling.innerHTML=" please enter mobile number";
return false;
}
if(isNaN(b))
{
document.getElementById("mobile").nextSibling.innerHTML=" only numbers are allowed";
return false;
}
if(b.length<10)
{
document.getElementById("mobile").nextSibling.innerHTML=" mobile number must be 10 digit";
return false;
}
if(b.length>10)
{
document.getElementById("mobile").nextSibling.innerHTML=" mobile number must be 10 digit";
return false;
}
}
<form onSubmit="return valid()">
HOME
<p><input type="text" name="user_name" id="user_name" value=""><span class="user_name"></span></p>
Mobile
<p><input type="text" name="mobile" id="mobile" value=""><span class="mobile"></span></p>
<p><input type="submit" value="submit"></p>
Maybe bec you are not returning any true statements with the b part. You have only error messages
If you can use HTML 5 form validation please do because it will do a lot of this stuff for you and is natively supported by modern browsers.
If not, I'm not exactly sure what you are trying to do but a few things I can see is you will return true before validating the second variable so put a return true at the end of the function and only return false when validation fails. Second once you return true the form will submit so your page is going to reload and unless you use your server side code to populate the span tags you won't see anything in them because the page was reloaded. The only other thing is to make sure your js doesn't get cached if you are loading it from a js file. Please let me know some more specifics on what is happening and I will be able to help more.
Maybe missing the return in front of true also but then everything after this statement would be unreachable.
if(a==correct_way)
{
true;
}
else
{
document.getElementById("msg").innerHTML=" username should be only charachter";
return false;
}
To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)
Hey guys I have a password validator that I amd having issues working on, its quite lengthy and I think can be shortened down and simplified if possible.
Could someone assist me in simplifying it. Im talking about the checkValidPassword() function.
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
// check the length of the password
checkValidPassword(input);
}
}
function checkValidPassword(input) {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value.length < 8) {
password.setCustomValidity('Password must contain at least 8 characters!');
} else {
var re = /[0-9]/;
if (!re.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
} else {
password.setCustomValidity("");
}
}
}
And im trying to implement a way for the user to must include atleast a number also. I was thinking about
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Would I include that in the if statment with $$ to symbolize and also check characters ?
if(password.value.length < 8 && str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)) {
This is essentially a code review question, but ok... I'd rewrite your function to something like:
function checkPassword() {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value != confirm_password.value) {
password.setCustomValidity('Password Must be Matching.');
return false;
}
if(password.value.length < 8 ) {
password.setCustomValidity('Password must contain at least 8 characters!');
return false;
}
if(!/[0-9]/.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
return false;
}
return true;
}
Basically, check each condition individually and return immediately if it fails, thus avoiding extra indentation ("early exits"). This is a bit verbose, but far more readable than a monster regular expression, especially if you don't know for sure what it does.
I managed to figure it out, I combined them both by just putting the else into one another.
function ValidatePassword(pass, confirm_pass) {
if (pass.value != confirm_pass.value || pass.value == "" || confirm_pass.value == "") {
confirm_pass.setCustomValidity("the Passwords do not match");
pass.setCustomValidity("the Passwords do not match");
} else {
if(pass.value.match(/(?=^.{8,30}$)([a-zA-Z]+[0-9])$/)) {
pass.setCustomValidity("");
confirm_pass.setCustomValidity("");
} else {
pass.setCustomValidity("the password doesnt have numbers");
confirm_pass.setCustomValidity("the password doesnt have numbers");
}
}
}
Here is what I made the form look like:
<form>
password
<input id="pass" type="password" required="" placeholder="Password" />
<br> confirm
<input id="confirm_pass" type="password" required="" placeholder="confirm" onfocus="ValidatePassword(document.getElementById('pass'), this);" oninput="ValidatePassword(document.getElementById('pass'), this);" />
<br> username :
<input id="username" required="" type="text">
<br>
<button class="btnform" name="register" type="submit">Complete Registration</button>
</form>
I have a form and currently I have a javascript code to validate my form to make sure that the user fills out every input. my form action includes:
onsubmit="return validateForm();"
Which is the javascript to make sure every field is filled out. If it makes any difference, here is my javascript code:
<script type="text/javascript">//
<![CDATA[function validateForm() {
var a=document.forms["myform"]["inf_field_FirstName"].value;
var b=document.forms["myform"]["inf_field_Email"].value;
var c=document.forms["myform"]["inf_field_Phone1"].value;
if (a==null || a=="" || a=="First Name Here")
{ alert("Please enter your First Name!");
return false; }
if (c==null || c==''|| c=="Enter Your Phone Here")
{ alert("Please insert your phone number!");
return false; }
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myform.inf_field_Email.value.search(emailRegEx) == -1)
{ alert("Please enter a valid email address.");
return false; } }
// ]]>
</script>
However on the phone number field, defined at c, I want to add another script that will pop up if the user doesn't enter a phone number at least 9 digits long. I was thinking of adding a code like this
<script type="text/javascript">
function validate(){
var c=document.forms["myform"]
if (input.length<9){
alert("Please enter a real phone number")
return false
}else {
return true
}
}
</script>
However I don't know how to run both functions on submit. I am extremely new to javascript so excuse me if there's already a simple solution to this.
Thanks
Everything in quotes after onsubmit= is just javascript. You can make sure both functions return true by doing:
onsubmit="return validateForm() && validate();"
You could add it as another rule in that conditional. For example:
if (c==null || c==''|| c=="Enter Your Phone Here" || c.length < 9) {
alert("Please insert your phone number!");
return false;
}
It's probably best to refactor this code, but that's probably the fastest way to do what you need.
I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>