Two textfield validation using JavaScript - javascript

I am building a registration form. I have two fields where a user can enter his email (one for email, the second is re-enter email). I am trying to validate the two fields to confirm they match. What I have done is that when a user moves to the password field, the onfocus will call the validate function and check if the two fields match. If there is an error, the error will display in another textfield. The problem is that the code is not working!!
Here is the code:
<html>
<head>
<script>
var fieldalias="Email address field"
function verify(element1, element2){
var passed=false
if (element1.value==''){
document.f1.emailerror.value='Fill out the first email field';
element1.focus()
}
else if (element2.value==''){
document.f1.emailerror.value='Fill out the second email field';
element2.focus()
}
else if (element1.value!=element2.value){
document.f1.emailerror.value='The two emails are not matching';
element1.select()
}
else
passed=true
return passed
}
</script>
</head>
<body>
<p>Username: <br/>
<input class="tb10" type="text" name="username" />
</p><br/>
<p>Email: <br/>
<input class="tb10" type="text" name="email1" />
</p>
<p>Re-Enter Email: <br/>
<input class="tb10" type="text" name="email2" />
<input id="emerror" type="text" readonly name="emailerror"/>
</p><br/>
<p>Password: <br/>
<input class="tb10" type="password" name="password1" onfocus="verify(this.email1,this.email2)";/>
</p>
</body>
</html>

There are a few problems. The first is in the way you call your function:
onfocus="verify(this.email1,this.email2)";
this will be the field that that event belongs to, i.e., the one getting focus, so it doesn't have email1 and email2 properties. (Note also you don't need a semicolon outside the quotes.)
Secondly, within your function you say:
document.f1.emailerror
But there is no f1 form in your html.
If you add a form element around your fields, give it the name f1, and update your inline onfocus as follows then it will work:
onfocus="verify(document.f1.email1,document.f1.email2)"
Demo: http://jsfiddle.net/jJ3YT/
Note: I don't really endorse the approach you've taken here - if it were me, I'd put the validation on blur out of both email fields, but only to display the message, not to force focus back into the first field. Then when the form is actually submitted if there is still a problem then maybe I'd force focus back to the problem field. But anyway for what you're trying to do you're almost there...

Related

Browser login autocomplete

I've implemented the login for the website where the user can have different account types for example:
Type A (default)
Username: characters and numbers
Password: characters and numbers
Type B (serial number)
Username: only numbers, min 10
Password: characters and numbers
When the user comes to the login form, first he/she is allowed to selected what type of login they want to use and then they proceed to the actual login.
Problem preconditions
The user has native Offer to save passwords enabled and have saved both Type A and Type B credentials to login, then logged out and eventually attempts to log in once again.
The "problem":
When the user will select Type A to login, will focus on the username the browser will suggest to prefil the field, but both Type A and Type B will be suggested by the browser.
The Question
Is there a way to somehow tag the credentials at the point of time when they are saved so next time the browser will suggest only corresponding credentials.
P.S: Any other possible solution or valuable information is more then welcome :)
UPDATE
After inspecting the specs: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill
I've added autocomplete="section-uniqueGroupName" and made sure that the name and id are unique.
Login with username
<form>
<input type="text" name="login-userName" id="login-userName" autocomplete="section-userName">
<input type="password" name="password-userName" id="password-userName" autocomplete="section-userName>
<button type="submit">Submit</button>
</form>
Login with card number
<form>
<input type="text" name="login-serviceCard" id="login-serviceCard" autocomplete="section-serviceCard">
<input type="password" name="password-serviceCard" id="password-serviceCard" autocomplete="section-serviceCard>
<button type="submit">Submit</button>
</form>
But still it doesn't seem to make the trick...
So the investigation continues and it makes me wonder if it is actually possible using only native approach html attributes without involving the JS achieve the following:
1. Separate user credentials by type of login
2. And (or at least) Autofill the last used credentials of selected type of login
If it's actually possible and there is an alive example on a web it will be much appreciated to be able to have a look :bowing:
The easiest solution that should work is to make sure that the names of the inputs are different. For example:
input {
width: 200px;
display: block;
}
form,
input {
margin-bottom: 5px;
}
input[type="number"] {
-moz-appearance: textfield;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
<form action="javascript:void()">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="Login" />
</form>
<form action="javascript:void()">
<input type="number" name="susername" pattern="\d{10,}" />
<input type="password" name="spassword" />
<input type="submit" value="Login" />
</form>
The browser should identify the inputs by their names, giving them different names should resolve the conflict.
If you name differently your Type A and Type B input, the browser will know it's a different input and will give suggestion according to the input selected by the user.
You can also add only Form Type A or B via JavaScript to the Document DOM after choosing one option.
I think the autofill takes into account the position in the HTML form.
So I suggest you to add them (both) in your form and to display only one at a time.
For example:
<form>
<input type="text" name="lgn-userName" id="login-userName" style="display:none">
<input type="text" name="lgn-serviceCard" id="login-serviceCard">
<input type="password" name="password" id="password">
<button type="submit">Submit</button>
</form>
Just, be aware, if you typed a lot of different login in the "first" (and only) input, you will get the suggestions in the first input with this trick. (At least on the same form)

How to set properties on other fields oninput with JQuery?

I have three inputs, and I'm trying to make it so that a user can enter any number of them, but at least one, in order to do a search. The backend is built to handle it just fine parsing these from the URL, but I'm having trouble client-side.
Right now, I'm using oninvalid and oninput like so:
<input type="text" id="Input1" name="Input1" required oninvalid=
"setCustomValidity('Please enter a valid Input1')" oninput="setCustomValidity('')"/>
What I'm trying to do is, in this package of 3 inputs, set the other two inputs to not be requiredand have a setCustomValidity value of '' when a value is entered in one of the fields. I also would like it to re-establish those rules if, say, the user were to change their mind after typing into the wrong field.
The JQuery I have right now:
jQuery(function ($) {
var $inputs = $("#Input1, #Input2, #Input3")
$inputs.oninput = (function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', false)
$inputs.not(this).prop("setCustomValidity", "")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="get">
<input type="text" id="Input1" name="Input1" required oninvalid="setCustomValidity('Please enter a valid Input1, 2, or 3')" oninput="setCustomValidity('')"/>
<input type="text" id="Input2" name="Input2" required oninvalid="setCustomValidity('Please enter a valid Input1, 2, or 3')" oninput="setCustomValidity('')"/>
<input type="text" id="Input3" name="Input3" required oninvalid="setCustomValidity('Please enter a valid Input1, 2, or 3')" oninput="setCustomValidity('')"/>
<input type="submit" value="Submit" />
</form>
Everything seems to compile correctly in Razor Pages etc with no errors, but the required properties are not being removed or changed. If anyone could offer insight into what I'm doing wrong, it'd be splendid; I'm new to JS and JQuery in general, but I can see it's powerful stuff.
setCustomValidity isn't a property or attribute, it's a function that you call from the oninvalid attribute. So it should be:
$inputs.not(this).removeAttr("oninvalid");
And when you want to re-establish it, use:
$inputs.not(this).attr("oninvalid", "setCustomValidity('Please enter a valid Input1')");
But I'm not sure you need to do this. Once you make it not required, it should never trigger the "invalid" event. So you don't need to remove it at all.
You can also do this with jQuery event listeners. To add the handler:
$elements.on("invalid", function() {
this.setCustomValidity("Please enter a valid input");
}
To remove it:
$elements.off("invalid");
You also have a typo in the assignment of $this. It should be:
var $inputs = $("#Input1, #Input2, #Input3");
And there is no jQuery .oninput() method. So it should be:
$inputs.on("input", function() {
...
});

Check $_POST data with jquery before submitting the form

I have a form that sends the store the First Name of the user in a database. I was checking the information send by the user using regex in php.
To make my project more interactive, I decided to validate the information jQuery before sending it to PHP.
My Project looks like this:
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
$(document).ready(function() {
$("form").submit(function (e) {
var firstname = $(this).find('input[name="firstname"]').val();
var regex = /^[A-Za-z0-9 \-']+$/;//Only numbers, Letters, dashes, apostrophes and spaces are accepted
if(regex.test(firstname)){
alert('Valid Name.');
}else{
alert('Invalid Name.');
e.PreventDefault();
}
});
});
</script>
Now I have 2 questions:
Is it really need to check the First Name in PHP again before storing the data in the database ? (To improve security)
How can I submit the form right after the alert('Valid Name.'); ?
Thanks for providing your help.
First of all have in mind that the validation of users input is implementing at the server side of an application only!!! You can not validate input data at client side with JS because it can be passed very easy(either by disabling javascript or by using tools like Curl).
However you can increase user experience like validate an input before submitting the form or inform the user that forgot to fill in an input.
To inform the user about a not fill in input you can just use the new html 5 attribute required like above
Username: <input type="text" name="usrname" required>
the required attribute will not let the user submit the form unless he had filled the associated input.
Also you can use the maxlength attribute to address a use case like "A password must have X max letters.
Password: <input type="password" name="pass" maxlength="8" size="8"><br>
How to validate input at server side
There are many techniques for this and you can find all of them here at Stackoverflow. Ι will refer the top voted post How can I prevent SQL injection in PHP? which answer exactly your question.
Just two bullets that compact the above post that i suggest you read otherwise
Always escape your data
Use mysqli instead of mysql
How can I submit the form right after the alert('Valid Name.'); ?
this is very easy just use this code
<form action="action_page.php" method="post">
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
the above code will "send" user's input for process at action_page.php using POST method, where you can read using $_POST supergloba table like $firstname = $_POST['fistsname'] etc.
TRY This
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js" ></script>
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" id="first_name" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
jQuery.validator.addMethod("firstName",function(value,element,param)
{
if(this.optional(element))
{//This is not a 'required' element and the input is empty
return true;
}
if(/^[A-Za-z0-9 \-']+$/.test(value))
{
return true;
}
return false;
},"Please enter a valid First Name");
$(function()
{
$('#myform').validate(
{
rules:
{
first_name:{ required:true, firstName:true }
}
});
});
</script>
Firstly you should ALWAYS validate server side for form submission, especially if you are passing those value along to a DB - SQL injection, the struggle is real.
As for the form submission flow you can...
return true
... after the valid name alert and the form to submit as it normally would.
Since you already have bound to that submit event, It would be even better for the user if you submitted the form via ajax, and providing feedback if the server validation fails. Thus the user never leaves the page and you are able to handle both client and server validation.
Take a look at ParsleyJS - http://parsleyjs.org/ - w00t!

Creating URL from form fields in javascript

So, i'm really new to HTML and javascript, and I want to take values from a form and process them with a script. I have a couple of fields including username, password, and two confirm password fields in HTML. With javascript I want to collect the username, and check if the password field is filled out. If it is, I want to make var ispass equal to 'yespass' or 'nopass'. When I submit the form, I want to go the url http://www.example.com?un=username&pass=yespass (or nopass).
Javascript:
<script language="javascript" type="text/javascript">
function processFormData(){
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var ispass;
if (pass.length > 0){
ispass = "yespass";
}else{
ispass = "nopass";
}
return "http://www.example.com?un=" + user + "&pw=" + ispass;
</script>
HTML:
<form onsubmit="window.location.href=processFormData();">
Please enter your current e-mail address and password below.<br><br>
<input type="text" id="username" placeholder="E-mail Address"><br><br>
<input type="password" id="oldpassword" placeholder="Old Password"><br><br><br>
Please type your new password below:<br><br>
<input type="password" id="newpassword1" placeholder="New Password"><br><br>
<input type="password" id="newpassword2" placeholder="Confirm New Password"><br><br>
<input type="submit" id="gobutton" value="Reset Password"/>
</form>
I cannot figure out a proper way to do this, because this does not seem to be working at all. Any suggestions or recommendations?
You could pull this off with a hidden form field and an onchange event:
<input type="hidden" id="ispass" value="no" onchange="checkPass(this);" />
This input would go in your form. Then on your password field, add an onchange handler:
function checkPass(input) {
document.getElementById("ispass").value = "yes"
};
Also, if you set the method on your form, submitting the form can generate the url based on the form inputs:
<form method='get' action='...' />
Here's a jsfiddle that demonstrates the result.
Also, if you're new to javascript, you may want to look into a library like jQuery to simplify some of your interaction with the page. It's really easy to learn, and there's a great community around it to help with any problems you might run into.
HTH,
Aaron

Change post form

I have simple login form in my website. In given requirements stands, that password mustn't been sent to server, but only MD5 hash. I took simple MD5 function and now, when with onClick on submit button I change hidden text from password to md5(password). This works fine, but user sees, that something with his password is happening. I would like to make it transparent and change this particular part of form dynamically with onPost (or smth like this) callback.
I can't find any tutorials how to deal with manipulating POST table/form in javascript (jquery?) so if anyone could help I would appreciate.
As far as I know input fields that don't have name don't get submitted to the server. So you could have a hidden field and in the onsubmit event of the form copy the value of the password field into the hidden field by applying the MD5 checksum:
<form method="post" action="/login">
<input type="password" id="password" />
<input type="hidden" name="password" id="hiddenpassword" />
<input type="submit" value="Login" />
</form>
and then:
$('form').submit(function() {
var password = $('#password').val();
var md5 = MD5(password);
$('#hiddenpassword').val(md5);
return true;
});

Categories