I want to stop the form from submitting when the username is below 3 characters. I tried using return false but it didn't work.
Below is the code (didn't used return false in this one)
I am a beginner so please give an easy explanation 😅
const messageElement = formElement.querySelector(".form__message");
messageElement.textContent = message;
messageElement.classList.remove("form__message--success", "form__message--error");
messageElement.classList.add(`form__message--${type}`);
}
function setInputError(inputElement, message) {
inputElement.classList.add("form__input--error");
inputElement.parentElement.querySelector(".form__input-error-message").textContent = message;
};
function clearInputError(inputElement) {
inputElement.classList.remove("form__input--error");
inputElement.parentElement.querySelector(".form__input-error-message").textContent = "";
};
document.addEventListener('DOMContentLoaded', () => {
const loginForm = document.querySelector("#login");
const createAccountForm = document.querySelector("#createAccount");
document.querySelector("#linkCreateAccount").addEventListener("click", e => {
e.preventDefault();
loginForm.classList.add("form--hidden");
createAccountForm.classList.remove("form--hidden");
});
document.querySelector("#linkLogin").addEventListener("click", e => {
e.preventDefault();
loginForm.classList.remove("form--hidden");
createAccountForm.classList.add("form--hidden");
});
loginForm.addEventListener("submit", e => {
e.preventDefault();
setFormMessage(loginForm, "error", "Invalid Username/Password Combination");
});
document.querySelectorAll(".form__input").forEach(inputElement => {
inputElement.addEventListener("blur", e => {
if(e.target.id === "signupUsername" && e.target.value.length < 3 ) {
setInputError(inputElement, "Username must be atleast 3 letters in length");
}
});
inputElement.addEventListener("input", e => {
clearInputError(inputElement);
});
});
});```
For me this always works:
function check_form(form) {
var ok = confirm("is it ok?");
return ok
}
<form onsubmit="return check_form(this)">
<input>
<input type="submit">
</form>
Bonus: if you want to asynchronously check the form and only then submit, it goes like this:
function check_form(form) {
setTimeout(function() {
var ok = confirm("is it ok?")
if (ok) {
form.submit()
}
}, 100);
}
<form onsubmit="check_form(this); return false;">
<input>
<input type="submit">
</form>
Related
html
<form>
<label>Enter Text: </label>
<textarea placeholder="Enter text here for detection." id="name" name="name" autofocus class="result" >
</textarea>
</form>
<div class="options" style="display:none">
<div class="anguage" >
<p>Language</p>
<select name="input-language" id="language"></select>
</div>
</div>
<button class="btn record" id='myid'>
<p><b> Start Listening</b></p>
</button>
<div style="margin-top:-50px;" class="buttons">
<button class="btn clear" id='clr' style="margin-left:150px" onClick="eraseText()">
<b>Clear</b>
</button>
</div>
Btn clear function
<script>
function eraseText(){
document.getElementById('name').value='';
}
</script>
Voice to Text conversion code
<script>
const languages = [
{
no: "16",
name: "English",
native: "English",
code: "en",
}
];
const recordBtn = document.querySelector(".record"),
result = document.querySelector("result"),
inputLanguage = document.querySelector("#language")
clearBtn = document.querySelector(".clear");
let SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition,
recognition,
recording = false;
function populateLanguages() {
languages.forEach((lang) => {
const option = document.createElement("option");
option.value = lang.code;
option.innerHTML = lang.name;
inputLanguage.appendChild(option);});
}
populateLanguages();
function speechToText() {
try {
recognition = new SpeechRecognition();
recognition.lang = inputLanguage.value;
recognition.interimResults = true;
recordBtn.classList.add("recording");
recordBtn.querySelector("p").innerHTML = "<p style='margin-top:8px'>Stop Listening...</p>";
recognition.start();
recognition.onresult = (event) => {
const speechResult = event.results[0][0].transcript;
//detect when intrim results
if (event.results[0].isFinal) {
result.innerHTML = " " + speechResult;
result.querySelector("p").remove();
}
else {
//creative p with class interim if not already there
if (!document.querySelector(".interim")) {
const interim = document.querySelector('textarea')
interim.classList.add("interim");
result.appendChild(interim);
}
//update the interim p with the speech result
document.querySelector("textarea").innerHTML =" " + speechResult;
}
};
recognition.onspeechend = () => {
speechToText();
};
recognition.onerror = (event) => {
stopRecording();
if (event.error === "no-speech") {
alert("No speech was detected. Stopping...");
} else if (event.error === "audio-capture") {
alert(
"No microphone was found. Ensure that a microphone is installed."
);
} else if (event.error === "not-allowed") {
alert("Permission to use microphone is blocked.");
} else if (event.error === "aborted") {
alert("Listening Stopped.");
} else {
alert("Error occurred in recognition: " + event.error);
}
};
}
catch (error)
{recording = false;
console.log(error);
}
}
recordBtn.addEventListener("click", () => {
if (!recording) {
speechToText();
recording = true;
}
else {
stopRecording();
}
});
function stopRecording() {
recognition.stop();
recordBtn.querySelector("p").innerHTML = "<b> Start Listening</b>";
recordBtn.classList.remove("recording");
recording = false;
}
</script>
I am converting voice to text in a textarea. When I load a page than the start listening button works perfectly, but when I press clear button than using the start listening button, it works but the data that I speak is not written to the textbox. For checking issue, I used alert statement for printing new data that is spoken in the alert box. The new data spoken is found and printed in the alert box.
I am confused why the new spoken data is not printing in the textarea box after using clear button when listening button working perfectly. Is there any way to get rid of this problem? I mean to say to solve this issue.
You declare this: const result = document.querySelector("result")
So the result, is the textarea element. Later do this:
function speechToText() {
...
if (!document.querySelector(".interim")) {
//const interim referd to the same element with const result
const interim = document.querySelector('textarea')
interim.classList.add("interim")
//and you add it as a child to itself.....???
result.appendChild(interim)
}
...
}
here's simple html form validated with JavaScript , it show error message when the required fields are empty and when username is short(not satisfy the required length)..but form is sending data when submit button is clicked even if errors are displayed....how can i properly validate this form?
here's the code
let form = document.getElementById("signUp");
let uname = document.querySelector("#userName");
let uemail = document.querySelector("#userEmail");
const showError = (input, message) => {
// get the form-field element
const formField = input.parentElement;
// show the error message
const error = formField.querySelector('small');
error.textContent = message;
};
const showSuccess = (input) => {
// get the form-field element
const formField = input.parentElement;
// hide the error message
const error = formField.querySelector('small');
error.textContent = '';
}
const validateForm = () => {
if (uname.value.trim() == "") {
showError(uname, "name is empty");
return false;
} else {
showSuccess(uname);
}
if (uemail.value.trim() == "") {
showError(uemail, "email is empty");
return false;
} else {
showSuccess(uemail);
}
return true;
}
const checkUsername = () => {
const username = uname.value.trim();
if (username.length < 3) {
showError(uname, 'Username must be atleast 4 characters')
return false;
} else {
showSuccess(uname);
}
return true;
}
form.addEventListener('input', (event) => {
switch (event.target.id) {
case 'userName':
checkUsername();
break;
}
});
form.addEventListener("submit", function(e) {
if (!validateForm()) {
e.preventDefault();
}
});
<h2>JavaScript Validation</h2>
<form id="signUp" name="myForm">
<div>
Name: <input type="text" name="uname" id="userName">
<small id="showMessage" class="form-text text-muted"></small>
</div>
<div>
<br> Email: <input type="email" name="email" id="userEmail">
<small id="showMessage" class="form-text text-muted"></small>
</div>
<div>
<button type="submit">sign up</button>
</form>
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)">
Here is my sample code:
<button onClick="CheckData()" type="submit">
I have some conditions in CheckData function:
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
Then I check:
if (warning.length>0) {
return confirm(warning);
} else {
return true; //also tried false
}
So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed.
Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form.
Any suggestions?
PS: This code is a demo and different from the real one. But the concept is the same.
You can pass in the event Object to the CheckData function and prevent the default action if the confirm returns false with event.preventDefault().
<form>
<button onClick="CheckData(event)" type="submit">Submit</button>
</form>
<script>
function CheckData(e){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
if(con){
return true;
} else {
e.preventDefault();
return false;
}
} else {
return true;
}
}
</script>
You can also return the result of CheckData so the default action will be prevented if it returns false.
<form>
<button onClick="return CheckData()" type="submit">Submit</button>
</form>
<script>
function CheckData(){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
return con;
} else {
return true;
}
}
</script>
Change your HTML to this:
<form onsubmit="return CheckData()">
<button type="submit" />
...
</form>
Explanation:
The onsubmit event handler is called when the form is submitted.
When the event handler returns false the submission is aborted.
I have added the following before end of head
<script src='https://www.google.com/recaptcha/api.js'></script>
I have added this before end of form
<div class="g-recaptcha" data-sitekey="== xxxxxx =="></div>
I can see the recaptcha similar to https://developers.google.com/recaptcha/
HOwever, when user presses data without checking the checkbox, the data is submitted. Is there any other code I need to add to check if user has pressed the checkbox? Hopefully in js?
Google has a call back option for when the checkbox is checked.
Add this to your form element:
data-callback="XXX"
Example:
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="== xxxxxx =="></div>
And a disable attribute to your submit button.
Example:
<button id="submitBtn" disabled>Submit</button>
Then a create a callback function and write whatever code you need.
Example:
function recaptchaCallback() {
$('#submitBtn').removeAttr('disabled');
};
You can also call the grecaptcha object to check. grecaptcha.getResponse(); is empty when unchecked and has the verification code when checked.
grecaptcha.getResponse().length === 0 when unchecked
function isCaptchaChecked() {
return grecaptcha && grecaptcha.getResponse().length !== 0;
}
if (isCaptchaChecked()) {
// ...
}
To check if google recaptcha is checked or not you can do it by the following code :
<script>
if(grecaptcha && grecaptcha.getResponse().length > 0)
{
//the recaptcha is checked
// Do what you want here
alert('Well, recaptcha is checked !');
}
else
{
//The recaptcha is not cheched
//You can display an error message here
alert('Oops, you have to check the recaptcha !');
}
</script>
To check if google recaptcha v2 is checked or not you can do it by the following code :
var checkCaptch = false;
var verifyCallback = function(response) {
if (response == "") {
checkCaptch = false;
}
else {
checkCaptch = true;
}
};
$(document).ready(function() {
$("#btnSubmit").click(function() {
if (checkCaptch && grecaptcha.getResponse()!="") {
//Write your success code here
}
});
})
Let the browser do the job for you! (based on slinky2000 answer)
note: this is only to prevent sending an 'accidentally' unchecked recaptcha. You still have to verify the recaptcha on server side because a bot does not care ...
Add a an invisible input tag with required=true attribute just below the div.g-recaptcha.
<input id='recaptcha_check_empty' required tabindex='-1',
style='width:50px; height:0; opacity:0; pointer-events:none;
position:absolute;
bottom:0;'>
Enclose both width a div with position=relative; to point the bottom:0; above to the bottom of recaptcha.
Now the Browser asks nicely to fill out this field - pointing to the recapcha.
Now we need the callback:
<div class="g-recaptcha" data-callback="recaptchaCallback" ...
and
function recaptchaCallback() {
$('#recaptcha_check_empty').val(1);
}
<div class="contact-inner contact-message">
<label for="message-text" class="col-form-label">CAPTCHA</label>
<div class="g-recaptcha" data-sitekey="<?php echo 6LfSJmocAAAAAFFMpMKB1CtYNJYDyDswO7GpxRXS ;?>">
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<!DOCTYPE html>
<html>
<head>
<title>CAPTCHA</title>
</head>
<body>
<div class="contact-inner contact-message">
<label for="message-text" class="col-form-label">CAPTCHA</label>
<div class="g-recaptcha" data-sitekey="<?php echo GOOGLE_KEY ;?>"></div>
</div>
</body>
</html>
if for some reason you are conditioning a form by hand like me, and required is not working.
First import ReCAPTCHA
import ReCAPTCHA from 'react-google-recaptcha'
Apply it in your component
<ReCAPTCHA style={{margin: '5px', transform: 'scale(0.8)'}} ref={recaptchaRef} sitekey={recaptchaKey} onChange={updateRecaptcha}/>
you can use a useRef or just use the ReCAPTCHA you've imported, I used useRef.
const recaptchaRef = useRef<any>()
And now, how do I check if recaptchaRef is checked?
if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
//your condition
}
basically, you are saying 'if recaptcha is true, then do this'
this is complete form code that helps you (I'm using typeScipt)
const Formid = // yout formid
const FormSpark = `https://submit-form.com/${Formid}`
type FormState = {
name: string,
mail: string,
message: string
}
const initialState = {
name: '',
mail: '',
message: '',
}
const [wrongmail, setWrongmail] = useState(false)
const [wrongname, setWronname] = useState(false)
const [wrongtext, setWrongtext] = useState(false)
const [alert, setAlert] = useState(false)
const recaptchaRef = useRef<any>()
const recaptchaKey = //your recaptcha public key const [recaptchaToken, setRecaptchaToken] = useState<string>()
const [formstate, setFormState] = useState<FormState>(initialState)
const submit = async(event: FormEvent) =>{
event.preventDefault()
await postSubmission()
}
const updateRecaptcha = (token: string | null)=>{
setRecaptchaToken(token as string)
}
const {name, mail, message} = formstate
const postSubmission = async() => {
const payload = {
...formstate,
"g-recaptcha-response": recaptchaToken
}
try {
if (name && mail && message) {
if (mail.includes('#') && mail.includes('.') && mail.length > 5) {
if (name.includes(' ') && name.length> 5) {
if (message.length > 20) {
if (recaptchaRef.current) {
if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
console.log('hola')
setAlert(true)
const result = await axios.post(FormSpark, payload)
setFormState(initialState)
recaptchaRef.current.reset()
if (result) {
setTimeout(() => {
setAlert(false)
},2000)
}
}
}
}
}
}
if (!name && !(name.length> 5) && !(name.includes(' '))) {
setWronname(true)
setTimeout(() => {
setWronname(false)
},3000)
}
if (!mail && !mail.includes('#') && !mail.includes('.') && !(mail.length > 5)) {
setWrongmail(true)
setTimeout(()=>{
setWrongmail(false)
},3000)
}
if (!message && !(message.length > 20)) {
setWrongtext(true)
setTimeout(() => {
setWrongtext(false)
},3000)
}
}
} catch(error){
console.log(error);
}
}
const updateForm = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const {id, value} = event.target
const formKey = id as keyof FormState
const updatedFormState = {...formstate}
updatedFormState[formKey] = value
setFormState(updatedFormState)
}