Set focus to another field in web form with javascript - javascript

I have a web form with two fields:
Email
User name
I want to track user input in the Email field and when it ends with ".com" set focus to another field "User email"
What the best way to do so with JavaScript or jQuery.

This should do the trick. When the last 4 letters of the email input are '.com', the focus is given to the username field.
While this works, please consider the UX issues this may cause. In the comments for your question, Quentin provides a good explanation of why this probably isn't worth implementing.
$('#email').on('input', function() {
email = this.value
if (email.substr(email.length - 4) === '.com')
$('#username').focus()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text" placeholder="email">
<input id="username" type="text" placeholder="user name">

as #Quentin mentioned this not a best practice due to these types of emails such as (.com.au)
but if you really know what you are doing then this code does what you want
// select email input
const mail = document.getElementById('mail');
// add input event
mail.addEventListener('input', e => {
// get value
let value = e.target.value.trim();
const regex = /.com$/ig; // matches any string ends with .com
const result = regex.test(value);
// if matches .com at the end then add focus to name input
if (result) {
e.target.nextElementSibling.focus();
}
});
<form>
<input type="text" placeholder="insert your email" id="mail">
<input type="text" placeholder="insert your name" id="name">
</form>

Related

Check if Form Input is Valid With JavaScript

I am currently trying to make a login / create account page for a website that I am developing for fun. In the create account form, I have an input field for username, name, email, password, and verify password. I also have patterns in the input fields so that the user makes valid account info. Here is the form below:
<form method="post" action="CreateAccount.php">
<h1>Create Account</h1>
<input class="inputInfo" type="text" name="username" id="newUsername" pattern="[A-Za-z0-9]+" placeholder="Username" maxlength="40" minlength="5" onkeyup="checkInput()" onblur="checkInput()" autocomplete="off" required/>
<input class="inputInfo" type="text" name="fullname" id="newName" placeholder="First and Last Name" onkeyup="checkInput()" onblur="checkInput()" minlength="3" autocomplete="off" required/>
<input class="inputInfo" type="email" name="email" id="newEmail" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" title="Must be a real email" placeholder="Email" onkeyup="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="password" id="newPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="verifypassword" id="verifyPass" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Verify Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<span><label for="showp"><input type="checkbox" id="showp" onclick="showPassword()">Show Password</label></span>
<button type="submit" style="margin-top: 7px;" class="disabled" id="submitButton">Sign Up</button>
<p style="font-size: 10px;">By signing up, you agree to our Terms , Data Policy and Cookies Policy .</p>
</form>
For clarification: the username pattern requires you to have a username with only upper and lower case letters and numbers and must be at least 5 characters and at most 40 characters. The email requires you to input a valid email address pattern. And the password requires a password that is at least 8 characters and must have an uppercase and lowercase letter and a number or special character.
In the input fields, you will see that I have a function called during blur or keyup event that is called checkInput(). The purpose of the function is to ensure that the input fields have the necessary length before the submit button can be enabled:
function checkInput ()
{
let usernameLength = document.getElementById('newUsername').value.length;
let nameLength = document.getElementById('newName').value.length;
let emailLength = document.getElementById('newEmail').value.length;
let passwordLength = document.getElementById('newPassword').value.length;
let verifyLength = document.getElementById('verifyPass').value.length;
if (usernameLength >= 5 && nameLength > 0 && emailLength > 0 && passwordLength >= 8 && verifyLength >= 8)
{
document.getElementById('submitButton').disabled = false;
const element = document.querySelector('#submitButton');
if (element.classList.contains('disabled'))
{
element.classList.remove('disabled');
}
}
else
{
document.getElementById('submitButton').disabled = true;
const addElement = document.querySelector('#submitButton');
addElement.classList.add('disabled');
}
}
I also have the following CSS classes that either make the border and shadow of the input field green or red:
.validInput {
border-color: #50c878;
box-shadow: 0 0 5px #50c878;
}
.invalidInput {
border-color: #ff0000;
box-shadow: 0 0 5px #ff0000;
}
My problem is that I would like to add some javascript so that while the user is typing in their information into the form, the code checks to make sure their input matches the patterns that are stated in the input fields. If the input they are putting into the field is valid, I would like for the javascript to add the validInput class to the input field. If the input is invalid I would like to add the invalidInput class to the input field. I have no idea, though, how to go about having JavaScript check if the input follows the pattern.
I would also like to make it to where it checks if the input is valid every time the user has a change event.
Does anyone have any ideas on how to go about doing this?
You can use the addEventListener function with 'change' parameter if you want your verification to run after the user leaves the field, or with 'input' parameter if you want the verification to run each time the user writes something in the text field. This should do it for you:
// If you want the verification to run when the user leaves the input.
document.getElementById('newUsername').addEventListener("change", checkInput);
// If you want the verification to run each time the user changes the input.
document.getElementById('newUsername').addEventListener("input", checkInput);
For the verification part, you can use regex. Create the verification functions first, (checks if the input is valid):
let check_username = (username)=>{
let rx = /^[a-z0-9]{8,40}$/i;
return rx.test(username); // Checks if the username is only made of alphanumeric characters (case insentisive)
}
let check_password = (password)=>{
let special_char = /[0-9!##\$%\^\&*\)\(+=._-]/; // If you want more special characters add them inside the braces at the end (after the '=+._-')
let upper_char = /[a-z]/;
let lower_char = /[A-Z]/;
return special_char.test(password) // Checks if the password contains a special character or a number
&& upper_char.test(password) // Checks if the password contains an upper case letter
&& lower_char.test(password) // Checks if the password contains a lower case letter
&& password.length>=8; // checks the password length
}
let check_email = (email)=>{
let rx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/;
return rx.test(email); // Checks the mail format.
}
Then you can use them like that:
check_username(document.getElementById('newUsername').value)
// This should return true if the username is valid or false if not.
Hope this was helpful. You can close the subject if that's what you are looking for.

Validate multiple input type="email" using Javascript

I have one form which contain multiple email field so this email to be submitted in database but before that it should validate to avoid duplication, (multiple email fields generated by click on add more button which is present in form ).
I have written ValidateEmail script to avoid duplication however it will work for only one email field but not successfull for multiple email field.
issue:
1) if we type email id in first field it will go for validation and check email exist or not if exist disable submit button if not exist enable button.
2) if we type type email id in second field and after validation it return email not exist then it will enable submit button however in first email field contain duplicate email.
3) if all email fields not contain duplicate values then only enable submit button else it should remain disabled..
<form>
<div>
<input type="email" name="email[]" class="email" onblur="validate_email(this)" /> // initially single filed
// This additional email fields created when click on add more button
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
</div>
<button class="add_more">Add more</button> // this will append extra email fileds
</form>
<script>
// This is the script it will check whether email already exist or not
function ValidateEmail(data) {
var email_id = data.value;
$.ajax({
type: "POST",
url: "<?= base_url('controller') ?>",
data:{
email_id:email_id
},
dataType: 'json',
success: function (response) {
if(response.exist){
// disable submit button and show error
}
else{
//enable submit field and hide error
}
},
error: function (jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
</script>
If you're using jQuery for this, you can use event delegation for dynamic inserted/removed element. As of now, those will be the email inputs.
Basically the idea here is:
Get the value of last changed/onblur input element.
Validate for existing email on server side (asynchronous check)
Scan through the current available email inputs, then validate and match each value with the Current Email in step (1).
If found, add a error class to the existing email field
Otherwise, add a valid class to the existing email field
You dont need to pass onblur="validate_email(this)" , this can be done in jquery.
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
function isEmail(email) {
// eslint-disable-next-line no-useless-escape
return RegExp(/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i).test(email);
};
function asyncEmailValidate(email) {
return new Promise(function(resolve, reject) {
if (data.includes(email))
return reject('Found duplicated')
return resolve(true);
})
}
$(document).ready(function() {
$(document)
.on('blur',"input.email", function(e) {
// Current email input
var currentEmail = e.target.value,
$emailNode = $(this),
isValid = true;
// Validate email
if (!isEmail(currentEmail))
return;
// Validate email on server side first,
// If found no existing email, then check
// siblings email for duplicates
var serverResult = asyncEmailValidate(currentEmail);
serverResult
.then(function(result) {
// There's no existing email with the inputed email. Now
// look up on other available email inputs fields, except
// the current one, and validate with the current email value
var siblingsEmailInputs = $("input.email").not($emailNode);
if (!siblingsEmailInputs)
return;
if (siblingsEmailInputs.length > 0) {
siblingsEmailInputs.each(function(index) {
console.log('input : ', $(this).val())
if ($(this).val() !== "" && $(this).val() === currentEmail) {
isValid = false;
}
});
}
// Finally update the state for the current field
if (isValid) {
$emailNode.addClass('is-valid');
} else $emailNode.addClass('is-error');
})
.catch(function(error) {
$emailNode.addClass('is-error');
console.log('error:', error);
})
});
})
.email.is-error {
border: 1px solid red;
}
.email.is-valid {
border: 1px solid green;
}
.email {
width: 300px;
margin: 5px;
height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
</pre>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
Those are just the basic way for you to handle email validation and duplicated emails. I think you can take it from here to work on your submit logic.
One quick note, you should leave the ajax submitting process in a separate function, not mixing up with validation process, it will be clearer.
Hope this help
Link working sample: https://codepen.io/DieByMacro/pen/jOOdWMr
Updated:
- I haven't used ajax with jQuery for a while so I'm not sure about the correct syntax, so I've replaced it with a Promised call which works the same as you make an asynchronous request. You can follow the updated version for your reference.

URL validation in text input

How do I validate the url in a text input if the user accidentally write on the text input before clicking submit?
Try below code, this will work for you
function urlLocate() {
var url = document.getElementById("url").value;
var regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (url != "") {
if (!regexp.test(url)) {
alert("Please enter valid url.");
} else {
window.location.assign(url);
}
}
else {
alert("Please upload an image.");
}
}
try this function for Url validation.
function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
try this function for validating url
function ValidURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
Use form and <input type="url"> to validate it. The form can only be submitted with the valid value(s).
$('form').on('submit', function(e){
e.preventDefault();
console.log('valid URL');
});
<form>
Input a URL: <input type="url" required><br>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I agree with #NoobTW and #Azer to use <input type="url"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url
Examples without any JS:
Demand a URL prefix but you can make one up yourself. Both http:// and bonk:// will be accepted as valid url prefixes.
<form>
<input type="url" required />
<input type="submit" value="Submit Now!">
</form>
URL validation by demanding that all url's start with either http:// or https://
<form>
<input type="url" pattern="https?://.+" required />
<input type="submit" value="Submit Now!">
</form>
Require https:
<form>
<input type="url" pattern="https://.+" required />
<input type="submit" value="Submit Now!">
</form>
https://html5-tutorial.net/form-validation/validating-urls/
With simple error message:
<form>
<input type="url" pattern="https://.+" required title="Requires https://" />
<input type="submit" value="Submit Now!">
</form>
If you wish to replace Default HTML5 Validation Message you can do it like this:
https://webdesign.tutsplus.com/tutorials/html5-form-validation-with-the-pattern-attribute--cms-25145#Replacing%20the%20Default%20HTML5%20Validation%20Message
type="url"
You can give the input type="url" to give it a simple validation as mentioned above.
<input type="url" required>
Please note that you should also give it the required attribute if a valid URL is required to submit the form.
pattern attribute
You can also give the input the pattern attribute if you want to add your own custom validation. The pattern attribute takes a regex pattern as it's value and will match it to the value of the input at validation. If you use a pattern attribute to do your own custom validation, you don't need to use the "url" input type. A simple text input will work as well.
<input type="text" pattern=".*\.[a-z]{2,}$" required>
The above is an overly simplified regex pattern that will only recognize very plain urls (like example.com) and should not be used for any serious validation. But you can change the pattern to any one of the patterns used in functions suggested in other answers, or some other pattern that fit your needs.
Both combined
<input type="url" pattern="https?:\/\/*" required>
The above is a simple example of a url input where a pattern attribute has been applied to make the validation a little bit stricter. This way the value of the input has to pass both the standard validation of a url input field, but it also has to pass the regex pattern to be validated. In the above example, the url has to begin with either http:// or https:// to pass validation.

JavaScript Prevent text entry if it does not meet parameters

When working with a JavaScript function I want to prevent characters from being entered into a form if they do not meet certain parameters. The original JavaScript code I used was:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
That function worked while I was using only 1 input point in my form, however when I tried to use that function over multiple inputs it would only affect the first one in the form.
When creating a function that could be reused by multiple input boxes I got the following code:
function validateLetter(dataEntry){
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
}
catch(InputError) {
window.alert(InputError)
return false;
}
return true;
}
The form I am using to input information is:
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the city you were born in:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter" name="letter" onkeypress="validateLetter()">
</p>
</form>
Does anyone know a way to translate the last line of the first function: document.getElementById("letter").value = replacedInput;
To something that can be re-used with the current code.
I tried:
dataEntry.value = replacedInput
But that did not seem to run/change the function at all
The problem is in textInput.replace() - you forgot the second parameter. So instead of textInput.replace(/[^A-Za-z]/g);, you need textInput.replace(/[^A-Za-z]/g, "");.
As noted in the MDN website:
The ID must be unique in a document, and is often used to retrieve the element using getElementById.
In your example above, you are using the same value for the ID attribute on all of the input fields. Also, the name attribute should be unique within forms. The answer provided here explains in greater depth. With that said, in the examples below I have modified your input fields in respect to the above.
First off, the initial function you provided was pretty close. One issue with it is that the replace() method would need a second parameter. This parameter can be a string or a function to be called for each match. In your case I believe you just want an empty string:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
Secondly, you can reference the current input field that is invoking validateLetter() by passing it along to the function as a parameter using the keyword this.
onkeypress="validateLetter(this);"
On a sidenote: You might achieve a better user experience using onkeyup instead of onkeypress. The example below utilizes this event instead so you can compare and judge for yourself.
Here is everything put together in a working example:
function validateLetter(target) {
var textInput = target.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
target.value = replacedInput;
}
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="maiden" name="maiden" onkeyup="validateLetter(this);" />
</p>
<p>Enter the city you were born in:
<input type="text" id="city" name="city" onkeyup="validateLetter(this);" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="street" name="street" onkeyup="validateLetter(this)">
</p>
</form>

Text as place holder for textbox input?

I notice that at some websites like http://academia.edu/, the signup form has some "place-holder" in their text input field. Such that in a textbox, there's no label but a rather slight font "First name" word inside the text box.
When using Firebug to investigate, I see the following code:
<input class="standard_text magic-default magic-default-on" id="user_first_name" name="user[first_name]" size="30" type="text" value="First Name">
It looks like there's some "magic" javascript happen behind the scene. But since I'm not familiar with javascript debugging yet, I can't trace out how they do that yet.
Does anyone know how to produce that effect?
For modern browsers you can use the HTML5 placeholder attribute.
This will achieve the result you're after without any Javascript and will scale (won't do anything) in older browsers.
<input placeholder="First Name">
To get this working in older browsers you can include a little bit of jQuery:
$('input:text').focus(function(){
if ( $( this ).val () === $( this ).attr ( 'placeholder' ) ) {
$(this).val('');
}
}).blur(function(){
if($(this).val() == "")
{
$(this).val($(this).attr('placeholder'))
}
}
);
Working Example
You have to create a "onFocus" event handler for the input box, and clear the value of said input box. Off course you only clear the value if it's the default value ("First Name" in your example), so that you don't clear away whatever user entered if he returns to the input later.
You could also attach a "onBlur" event handler, and restore the value of the input box back to the default value (if user didn't enter anything).
<input id="user_first_name" name="user[first_name]" size="30" type="text" value="First Name" onFocus="inputFocus('First Name', this)" onBlur="inputBlur('First Name', this)">
<script type="text/javascriptt">
function inputFocus(ph, el){
if(el.value == ph)
el.value = "";
}
function inputBlur(ph, el){
if(el.value == "")
el.value = ph;
}
</script>
HTML5 placeholder is what you're looking for:
http://diveintohtml5.info/forms.html
In your case it would be:
<input name="firstname" placeholder="First name">
But also you can do it 100% with javascript:
http://lab.dotjay.co.uk/experiments/forms/input-placeholder-text/

Categories

Resources