Password checking in dojo - javascript

I want to check that two passwords are the same using Dojo.
Here is the HTML I have:
<form id="form" action="." dojoType="dijit.form.Form" />
<p>Password: <input type="password"
name="password1"
id="password1"
dojoType="dijit.form.ValidationTextBox"
required="true"
invalidMessage="Please type a password" /></p>
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
invalidMessage="This password doesn't match your first password" /></p>
<div dojoType="dijit.form.Button" onClick="onSave">Save</div>
</form>
Here is the JavaScript I have so far:
var onSave = function() {
if(dijit.byId('form').validate()) { alert('Good form'); }
else { alert('Bad form'); }
}
Thanks for your help. I could do this in pure JavaScript, but I'm trying to find the Dojo way of doing it.

This will get you a lot closer
setting intermediateChanges=false keeps the validator running at every keystroke.
the validation dijit's constraint object is passed to its validator. Use this to pass in the other password entry
dijit.form.Form automatically calls isValid() on all its child dijits when it's submitted, and cancels submittion if they don't all validate. I though the invalid ones would get their error message, but they don't. That's left as an exercise for the reader ;-)
the validation function:
function confirmPassword(value, constraints)
{
var isValid = false;
if(constraints && constraints.other) {
var otherInput = dijit.byId(constraints.other);
if(otherInput) {
var otherValue = otherInput.value;
console.log("%s == %s ?", value, otherValue);
isValid = (value == otherValue);
}
}
return isValid;
}
function onsubmit()
{
var p1 = dijit.byId('password1').value;
var p2 = dijit.byId('password2').value;
return p1 == p2;
}
and the input objects:
<p>Password: <input type="password"
name="password1"
id="password1"
dojoType="dijit.form.ValidationTextBox"
required="true"
intermediateChanges=false
invalidMessage="Please type a password" /></p>
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
constraints="{'other': 'password1'}"
validator=confirmPassword
intermediateChanges=false
invalidMessage="This password doesn't match your first password" /></p>

Even easier, use the pre-written Dojox widget, dojox.form.PasswordValidator.
http://docs.dojocampus.org/dojox/form/PasswordValidator
It does everything you want straight out of the box!

I've solved it!
This page on the Dojo forum was helpful.
I changed the HTML for the confirm password to:
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
validator="return theSame(this, dijit.byId('password1'));"
invalidMessage="This password doesn't match your first password" /></p>
The only difference is the added validator parameter.
And I created the following JavaScript function:
function(dojoTxt1, dojoTxt2) {
return dojoTxt1.getValue() == dojoTxt2.getValue();
}
I think you can also use the validator parameter to create regular expressions to test against, but the documentation isn't very clear.

Related

Adding *Required next to an empty input

So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.

HTML form using javascript to validate login credentials?

I have written the below code to make a simple form for validation of form inputs through javascript. Here username and passwords are written in the JS code, but it still shows alert message of the else loop even if giving correct credentials on the form.
Please Help?
var user = document.getElementById('username')
var pass = document.getElementById('password')
function user1() {
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" Placeholder="enter username"><br>
<input type="password" name="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
There are a few errors here:
You need to get the values of your inputs
You want to get those values when the button is clicked. Your code is grabbing them only when the page loads. Move the variable assignment into your function
You didn't give the elements ID attributes
function user1() {
var user = document.getElementById('username').value
var pass = document.getElementById('password').value
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" id="username" Placeholder="enter username"><br>
<input type="password" name="password" id="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
Also note that a button's default type is submit which will submit your form and reload the page after the alert is shown when clicked, so you might want to change that to type="button" to prevent that.

How to validate for either form fields with vanilla JavaScript

I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form" action="" method="POST">
<input type=hidden name="" value="">
<input type=hidden name="" value="">
<p class="errmsg" id="name_errormsg"></p>
<input id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
<input id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
<input id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />
<textarea id="description" name="description" placeholder="How can we help you?"></textarea>
<input type="submit" name="submit" value="Send message">
</form>
$(document).ready(function() {
$overlay = $(".modal-overlay");
$modal = $(".modal-frame");
$modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
if($modal.hasClass('state-leave')) {
$modal.removeClass('state-leave');
}
});
$('.form-close-button').on('click', function(){
$overlay.removeClass('state-show');
$modal.removeClass('state-appear').addClass('state-leave');
});
$('#contactformbtn').on('click', function(){
$overlay.addClass('state-show');
$modal.removeClass('state-leave').addClass('state-appear');
});
var formHandle = document.forms[0];
formHandle.onsubmit = processForm;
function processForm(){
var emailInput = document.getElementById('email');
var emailValue = emailInput.value;
var phoneInput = document.getElementById('phone');
var phoneValue = phoneInput.value;
var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
var regexEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
nameErr = document.getElementById("name_errormsg");
nameErr.innerHTML = "Please enter your phone number or a valid email address.";
nameErr.style.color = "red";
return false;
}
}
});
If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.
Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
....
Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?

Why isn't my span being displayed? Simple password matching

So I have a simple HTML form for users to enter username and passwords and I'm validating that the passwords match using JavaScript. However for some reason I can't get the span to display whether or not the passwords match.
window.onload = init;
function init(){
function passMatch(){
console.log("Matching words.");
var pwd1 = document.getElementById("pwd1").value;
var pwd2 = document.getElementById("pwd2").value;
var output1 = document.getElementById("pwd1Hint");
var output2 = document.getElementById("pwd2Hint");
if (pwd1 === pwd2){
output1.innerHTML = "Yes!";
console.log(output1.textContent);
} else {
output1.innerHTML = "No!";
console.log(output1.textContent);
}
}
// event handlers
document.getElementById("pwd1").onchange = passMatch;
document.getElementById("pwd2").onchange = passMatch;
}
And here is the relevant HTML...
<fieldset name="LoginInfo"><input size="30" placeholder="username"
name="username" id="username" type="text"> <br>
<br>
Password:<br>
<input size="30" required="required" placeholder="password" name="pwd1"
id="pwd1" type="password"> <span class="hint" id="pwd1Hint">Password
is too short (must be at least 8 characters)</span> <br>
Repeat Password:<br>
<input size="30" required="required" placeholder="password" name="pwd2"
id="pwd2" type="password"> <span class="hint" id="pwd2Hint">Passwords
don't match</span><br>
I'm going to stab at this with limited information, but you said something very interesting to me:
I can't even get the span to display its default text of "Password is
too short (must be at least 8 characters)" when the page loads
But our Fiddle's are working for you. This is static text independent of JavaScript. That tells me that you might have CSS that we are not seeing which is hiding your span.
My guess is that your init function is never being called. Try just calling that function below the definition - so just define it and then below it add init(). That works in this fiddle:
https://jsfiddle.net/awt3dxdj/
Then you can just make it an anonymous function that is executed immediately (IIFE).

JavaScript form validation code is not giving desired results

I have a subscription form on my website that I am trying to validate. When the user clicks the button signup the function validate() is called and the fields should get validated however im not getting it to work.
Obviously there are some errors in my code. I have tried to fix it with the little knowledge I have, but can't get it to work. I would greatly appreciate it if you could point me into the right directions as to what I am doing wrong.
Code follows:
function validate()
{
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var nat = document.getElementById("nat").value;
var address = document.getElementById("address").value;
var town = document.getElementById("town").value;
var zip = document.getElementById("zip").value;
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var password2= document.getElentById("password2").value;
if (name == "" )
{
window.alert("Please Enter your Full Name")
}
checkNr= isNaN(phone)
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
if (nat == "")
{
window.alert("Please enter your nationality")
}
if (address == "")
{
window.alert("Please Enter your address")
}
if (password != password2)
{
window.alert("Your passwords did not match. Please re-enter")
}
}
</script>
HTML:
<form name="subscribe">
FULLNAME: </strong><input type="text" id="name"/><br />
PHONE NR: <input type="text" id="phone" onblur="validateForm()" /><br />
NATIONALITY:<input type="text" id="nat" /><br />
Address:<input type="text" id="address" /><br />
Town:<input type="text" id="town" /><br />
Zip Code: <input type="text" id="zip" /><br />
Username: <input type="text" id="userName" /><br />
Password:<input type="password" name="password" /><br />
Retype:<input type="password" name="password2" /><br />
<input type="button" value="submit" onclick="validate()" />
</form>
I found these mistakes in your code:
there is no validateForm() function specified in your phone input field
if you want your form to send data, set the type submit, not button on your submit button
if you want to stop the form submitting when something is not filled, hook the onsubmit event of the form:
<form onsubmit="return validate()"> ... // note the return keyword
and the script
function validate() {
...
if(somethingIsWrong) return false; // false stops submitting
else return true; // do submit
}
also note the getElentById typo mentioned by #FranciscoAfonzo
I found my mistake. It looks like you can not use the document.get with a password input field. I took out the password and it worked. It would be great if I could get some input from someone more experience as to why.
A couple of suggestions:
In JavaScript comparisions are done using === (equal to) and !== (not equal to).
If you have only the variable name in the if loop that will also suffice.
Like:
if (address)
{
window.alert("Please enter your address")
}

Categories