I'm setting up web page (sign in page) where the user supposed to fill his personal info (just like a regular sign in page) but, the main purpose here is to check whether the user submitted his data properly and if not he would be notified by an alert message. My problem is with the functions which for some reason sometimes works and sometimes do not work.
The code is not fully completed but I can't continue with basic errors such as mine
I tried to find the solution in Stack Overflow and lots of js tutorials. Tried find a missing ";" or any other basic mistake that a beginner can do.
function goSign() {
var src = "signinpage.html"
window.open(src);
}
function checkAge() {
const x = document.forms["ageForm"]["age"].value;
const regex = /^\d{2}$/;
if (!x.match(regex)) {
alert("Must input numbers not longer than 2 digits");
return false;
}
}
function checkUsern() {
const username = document.forms["userForm"]["username"].value;
const regex = /^[A-Za-z0-9]+$/;
alert(
return namelen);
var minlen = 10;
if (minlen > username.length) {
alert("Your username must have atleast 10 characters");
return false;
}
}
<h1>Signin</h1>
<p>Please fill your details as requested</p><br>
<form name="nameForm" action="" onsubmit="return checkName()" method="post">
Full Name:<br>
<input type="text" name="fullname" />
</form>
<form name="ageForm" action="" onsubmit="return checkAge()" method="post">
Age:<br>
<input type="text" name="age" /><br>
<input type="submit" value="Submit" />
</form>
<form name="userForm" action="" onsubmit="return checkUsern()" method="post">
Username:<br>
<input type="text" name="username" /><br>
</form>
The expected output from those functions is, let's say the user entered a 3 digit number in his Age so he should be alerted "Must input numbers not longer than 2 digits", but instead the input just disappears and nothing happens.
Same thing with username.
Note: my main goal to do only 1 submit button that checks all the user's input but i dont know how to do it so instead i just apply a function and a submit button for every user input to make sure that the functions work properly...
The issue lies within return checkName() in the onsubmit handler for your inputs
The handler expects a function, so you should be fine to just write onsubmit="checkName"
Related
<form action="#" method="post" id="book-list">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" class="form-control">
</div>
<input type="submit" value="Add" class="btn btn-primary btn-block">
</form>
<script type="text/javascript">
function isEmail(email){
return /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z](2,4))$/.test(email);
}
const form = document.querySelector('#book-list').addEventListener('submit',(e) =>{
e.preventDefault();
const inputEmail = document.querySelector('#email').value;
if(isEmail(inputEmail) === false ){
console.log('you lost');
document.querySelector('#email').focus();
return false;
}else{
console.log('you win');
return true
}
});
</script>
Playing around with this email validation, is there anything wrong
with the code? even I filled the field with the proper email address like myname#gmail.com it kept
printing you lost result instead of printing the you win, is it because the form submit?
You can use input type='email' if you want to allow html5 to do the validation for you, the submit wont fire if the field is not valid.
Otherwise you can change your regexp a bit to the below one
([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})
The problem with your regular expression is the syntax for 2 to 4 characters.
Instead of (2,4) it should be {2,4}
function isEmail(email){
return /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(email);
}
isEmail('email#example.com')
// true
However, you may want to just use HTML's built in email type for your input. This will probably be more reliable than any regular expression you could could craft.
Your regular expression in the function isEmail is not correct. Change it to this
function isEmail(email){
return /^([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)$/.test(email);
}
Then you will get the right response when you submit with a valid email.
I currently have this code for a custom DuckDuckGo search bar:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>
It automatically opens the URL https://duckduckgo.com/?q={{SEARCH}} when you enter text in the box and press the enter key.
How could I make this bar go to a domain if one is entered? Optimally, it wouldn't validate the domain, just if it sees a string in the pattern xxxx.* with no spaces, it would open that page in a new tab.
Thank you for any help!
One way to solve it is by capturing the submit event of the form, analyze the input value and when it is a domain, open a new window with the domain and cancel the submit by returning false. In case of not being a valid domain, let the form proceed as usual by returning true.
Your html:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>
Your javascript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}
So one way to handle it is to use an if condition and check the string against a RegExp that recognizes domain names.
Here's a nifty one you can use:
/[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
I assume you don't need help getting the value from your text field or the actual redirection. However, if you needed more help, comment below and I'll post a more complete answer. The code below should help you get to where you want:
var domainRegExp = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
var pass = domainRegExp.test('test.com')
var fail = domainRegExp.test('test')
console.log(pass, 'pass')
console.log(fail, 'fail')
So as you can see the value inside the 'pass' variable is true, and 'fail' is false.
I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.
Im doing a website project in my first year in college and i need to get local storage working. All i need is to input information of my website form and then display the local storage in another form on antoher page. i had it working but i added extra inputs, i made sure my ids and names were correct but it still wont work. Heres a part of all 4 files. I need this as it is right now but for some reason it wont work. I cant use anything new.
!(http://i57.tinypic.com/9hkjfd.png)
<form action="readLocalStorage.html" method="post" name="form1" id="form1" onsubmit="return validateForm()">
<fieldset>
<legend>Sign Up</legend>
<label for="username">Create a Username</label>
<input type="text" placeholder="5 characters" name="username" id="username" required><br><br>
<form name="LSdata" id="LSdata" action="addContact.php" method="post">
<label>Username</label>
<input name="username" id="username" readonly /><br />
function writeLocalStorage() {
localStorage.username = document.form1.username.value;
}
function getLocalStorage() {
document.LSdata.username.value = localStorage.username;
}
It looks like your variables are mismatched. You are setting username but getting Username. In JavaScript, variables are case sensitive so username will not always equal Username, they are two different variables.
Using your functions:
function writeLocalStorage() {
localStorage.username = 'mike';
}
function getLocalStorage() {
console.log(localStorage.Username); // what you currently have, will return undefined
console.log(localStorage.username); // returns "mike"
}
// returns:
// undefined
// mike
getLocalStorage();
There are other questions regarding validating email addresses with javascript. There are also questions regarding validating forms. However I cannot get my code to work, and cannot find a question to cover this particular issue.
Edit
I totally understand that in a live website, server side validation is vital. I also understand the value of sending email confirmation. (I actually have a site that has all these features). I know how to code spam checks in php.
In this instance I have been asked to validate the email input field. I have to conform to xhtml 1.0 strict, so cannot use the type "email", and I am not allowed to use server side scripts for this assignment. I cannot organise email confirmation, it has to be totally checked via javascript.
I hope this clarifies my question
I am trying to validate a form for two things.
To check that all fields have data.
To see if a valid email address is entered.
I am able to validate a form fields for data, but trying to incorporate the email check is a trouble for me.
It was giving alerts before, but incorrectly, now it is not being called at all (or at least that is how it is behaving).
Once I get this working I then need to focus on checking if the email addresses match. However this is an issue outside of this question.
I am only focused on validating this in javascript. I am not concerned about server side in this particular instance (another issue outside of this question). Thanks.
function Validate()
{
var inputs = [document.getElementById('fname'),_
document.getElementById('lname'), document.getElementById('email1'),_
document.getElementById('email2')];
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
alert('Please complete all required fields.');
return false;
}
else if ((id =='email1' || 'email2') &&_
(inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}
}
}
<form onsubmit="return Validate()" action="" method="post" id="contactForm" >
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" name="email1" id="email1" />
<input type="text" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
A side note - to format text that wraps, is it ok (for the purposes of posting a question, to add and underscore and create a new line for readability? In the actual text I have it doesn't have this! Please advise if there is a simpler way to format my code for posts. Thanks again.
Edit 2
It works when I comment out this:
/*else if ((id =='email1' || id=='email2') && (inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}*/
So this helps with the trouble shooting.
I already see a syntax error there :
else if ((id =='email1' || 'email2')
should be
else if ((id =='email1' || id=='email2')
from where I see it.
Note also that entering a space in any field will also pass through the test : you should trim your field values when testing for empty ones.
finally, concerning validating the email, this is not how you use regex. Please read this post for a demonstration on how to validate an email in javascript+regex.
var a=document.getElementById('fname');
var b=document.getElementById('lname');
var c=document.getElementById('email1');
var d=document.getElementById('email12')
if(a==""||b==""||c==""||d=="")
{
alert('Please complete all required fields.');
return false;
}
The best thing to do with validating an email address is to send an email to the address. Regex just doesn't work for validating email addresses. You may be able to validate normal ones such as john.doe#email.com but there are other valid email addresses you will reject if you use regex
Check out Regexp recognition of email address hard?
AND: Using a regular expression to validate an email address
I worked out the solution to my problem as follows. I also have in here a check to see if emails match.
// JavaScript Document
//contact form function
function ValidateInputs(){
/*check that fields have data*/
// create array containing textbox elements
var inputs = [document.getElementById("fname"),_
document.getElementById("lname"), document.getElementById("message"),_
document.getElementById("email1"), document.getElementById("email2")];
for(var i = 0; i<inputs.length; i++){
// loop through each element to see if value is empty
if(inputs[i].value == ""){
alert("Please complete all fields.");
return false;
}
else if ((email1.value!="") && (ValidateEmail(email1)==false)){
return false;
}
else if ((email2.value!="") && (EmailCheck(email2)==false)){
return false;
}
}
}
function ValidateEmail(email1){
/*check for valid email format*/
var reg =/^.+#.+$/;
if (reg.test(email1.value)==false){
alert("Please enter a valid email address.");
return false;
}
}
function EmailCheck(email2){
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
if ((email2.value)!=(email1.value)){
alert("Emails addresses do not match.");
return false;
}
}
<form onsubmit="return ValidateInputs();" method="post" id="contactForm">
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" onblur="return ValidateEmail(this);" name="email1" id="email1" />
<input type="text" onblur="return EmailCheck(this);" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>