Validate empty string in form - javascript

I have a form that takes the users input and concatenated that to a url (written in function). How do I check to see if the users value is empty and have an alert appear right below the form that says "Please enter a valid store URL". With out having to re write my entire function! Help!
Input form
<form id="url">
<input type="text" name="urlName">
<button onclick="return myFunction()">Try it</button>
</form>
Javscript Function
document.getElementById("url").addEventListener("submit", myFunction);
function myFunction() {
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
Check empty string I have not working
function valInput() {
if (input.value.length === 0){
alert("need valid store URL")
}
}

In myFunction you can simple add this code after creating a new instance of FormData:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You call the myFunction twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction.
And in HTML you don't need button. You can add input:submit which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>

You can add an onBlur handler to the input.
function validate(val) {
if(val.trim() === "") {
alert("Field is required");
}
}
<input type="text" name="urlName" onblur="validate(this.value)">

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Mask the first 2 characters in input form

Hello i trying to hide/change (with *) the 1-st and 2-nt characters in input form, but value do not changed.
E.x if in my input form i put sarahlovecode in input form show **rahlovecode, but when submit get the full value sarahlovecode
HTML:
<input type="text" class="input" name="secret_word" id="secret_word">
And Js i using is:
$.fn.mask = function( regexp, matchGroup, callback ) {
this.on("blur", function(e){
$(this).data("value", this.value);
var result;
while (result = regexp.exec(this.value)) {
var matches = result.slice(1);
if (callback){
var substitute = callback(matches[0]);
} else {
var substitute = Array(matches[matchGroup-1].length + 1).join("*");
}
matches[matchGroup-1] = substitute;
this.value = matches.join("");
}
})
this.on("focus", function(e){
this.value = $(this).data("value") || "";
});
}
// With Regular expression
phoneRegexp = new RegExp("(.*?)(.{1})$", "g");
$("#secret_word").mask(phoneRegexp, 2);
ref: https://www.sitepoint.com/community/t/mask-input-fields-without-affecting-validation/37100/15
And it's working but change the value with **, same as input word.
Suggestion to fix this?
Thanks.
You need to change the value of the input back when you submit the form. Add a function on the event "onsubmit" of the form:
<form onsubmit="fix_asterisk();">
<fieldset>
<input type="text" class="input" name="secret_word" id="secret_word">
</fieldset>
<input type="submit">
</form>
Then in the javascript add the function:
<script>
function fix_asterisk(){
let input = document.getElementById("secret_word");
input.value = $(input).data("value");
}
</script>

How to save data from a form with HTML5 Local Storage?

I have a form that makes logging into a website but not in mine and I want them to be saved form data in my web with HTML5 local storage. But not how. Any idea? My form is this:
<form action="http://issuefy.ca.vu/on/login.php" class="form-login" method="post" />
<input name="email" type="email" id="email" required="" placeholder="Email" />
<input name="password" type="password" required="" placeholder="Contraseña" />
</form>
LocalStorage has a setItem method. You can use it like this:
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
When you want to get the value, you can do the following:
var storedValue = localStorage.getItem("email");
It is also possible to store the values on button click, like so:
<button onclick="store()" type="button">StoreEmail</button>
<script type="text/javascript">
function store(){
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
}
</script>
Here's a quick function that will store the value of an <input>, <textarea> etc in local storage, and restore it on page load.
function persistInput(input)
{
var key = "input-" + input.id;
var storedValue = localStorage.getItem(key);
if (storedValue)
input.value = storedValue;
input.addEventListener('input', function ()
{
localStorage.setItem(key, input.value);
});
}
Your input element must have an id specified that is unique amongst all usages of this function. It is this id that identifies the value in local storage.
var inputElement = document.getElementById("name");
persistInput(inputElement);
Note that this method adds an event handler that is never removed. In most cases that won't be a problem, but you should consider whether it would be in your scenario.
Here,Simple solution using JQUERY is like this..
var username = $('#username').val();
var password = $('#password').val();
localStorage.setItem("username", username);
localStorage.setItem("password", password);
To save the data you have to use
localStorage.setItem method and to get the data you have to use
localStorage.getItem method.
This is my function from my CMS, that save all TEXTAREA and INPUT values on "keyup"
and place it in the right element on reload.
After the form has been submitted, only the submitted form is deleted from the local storage.
Set it to buttom of your page, thats it.
(function (mz,cms,parentKey,subKey) {
setTimeout(function() {
const storeAll = "textarea,input";
const formArray = mz.querySelectorAll(storeAll);
parentKey = window.location.href+"-";
formArray.forEach((formItem) => {
if (formItem) {
subKey = formItem.getAttribute("name");
var key = parentKey+subKey;
if (localStorage[key]) {
var _localStorage = localStorage[key] ;
formItem.value = _localStorage;
}
formItem.addEventListener("keyup", function () {
var _localStorage = formItem.value;
var T = formItem.getAttribute("type");
if (T == "password" || T == "hidden" || T == "submit" || formItem.disabled) {
//console.log("Ignore: "+formItem.getAttribute("name"));
return;
}
localStorage.setItem(key, _localStorage);
} , false);
formItem;
}
});
const submitForm = mz.querySelectorAll("form");
submitForm.forEach((submitItem) => {
if (submitItem) {
submitItem.addEventListener("submit", function (e) {
// e.preventDefault();
const formArray = submitItem.querySelectorAll("textarea,input");
formArray.forEach((formItem) => {
subKey = formItem.getAttribute("name");
localStorage.removeItem(parentKey+subKey);
} , false);
} , false);
}
});
}, 1);
}(this.document,'','',''));

Swap default field value using pure JavaScript

I've written some code in jQuery for removing/replacing the default value of an e-mail field on focus and blur events. Its' working fine,
But I wanted it in JavaScript .. I've tried several times but I couldn't succeed.
here's my jQuery Code
$(document).ready(function(){
var email = 'Enter E-Mail Address....';
$('input[type="email"]').attr('value',email).focus(function(){
if($(this).val()==email){
$(this).attr('value','');
}
}).blur(function(){
if($(this).val()==''){
$(this).attr('value',email);
}
});
});
can anyone tell me how to do it in JavaScript,
Assuming <input type='text' id="email_field"/>
var email = 'Enter E-Mail Address....';
var emailField = document.getElementById("email_field");
emailField.onfocus = function(){
removeDefaultText(this);
}
emailField.onblur = function(){
setDefaultText(this);
}
function removeDefaultText(element){
var defaultValue = 'Enter E-Mail Address....';
if(element.value == defaultValue){
element.value = "";
}
}
function setDefaultText(element){
var defaultValue = 'Enter E-Mail Address....';
if(element.value == ''){
element.value = defaultValue;
}
}
Apparently you're trying to display a placeholder value, when there is no other value.
In any modern browser, you might simply use this:
<input type="text" class="email" placeholder="Enter E-Mail Address..." />
Unfortunately that excludes older IEs, so an approach for vanilla JavaScript could be like this:
// grab all input[type="email"] elements
var emailFields = document.getElementsByTagName('INPUT').filter(function(input) {
return input.type === 'email';
});
var placeholder = 'Enter your E-Mail Address...';
// watch onfocus and onblur on each of them
emailFields.forEach(function(input) {
input.onfocus = function() {
// clear only if the value is our placeholder
if (input.value === placeholder) {
input.value = '';
}
}
input.onblur = function() {
// set the value back to the placeholder, if it's empty
if (input.value === '') {
input.value = placeholder;
}
}
});
Hope that suits your needs.
try
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}
with jQuery
var userinputmail= $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinputmail))
{
alert('not a valid e-mail ');
}​
You can also try the following regex for other validation (I think this will helpful)
Matching a Username => /^[a-z0-9_-]{3,16}$/
Matching a Password => /^[a-z0-9_-]{6,18}$/
Matching a URL => /^[a-z0-9_-]{6,18}$/
You can use regular old javascript for that:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
======
using new regex
demo http://bit.ly/Hzbq4i
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex
email check exists!
check this link

Categories

Resources