<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.
Related
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"
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.
I have a webpage where a user submits a form containing an email field and a confirm email field.
How do I check to make sure both of these fields equal the same thing?
<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>
With jQuery, but no error handling, I'd suggest:
$('form').on('submit', function() {
return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});
Ridiculously simple JS Fiddle demo.
Easiest way would be to use Javascript as you can stop form submission before it goes to your php file. However it is still good practice to verify the data entered with the php file as well as there are some programs that will allow you to change data being submitted in a form after javascript checks are made.
<script>
function checkMatch() {
var email = document.getElementById('email').value;
var emailConfirm = document.getElementById('emailConfirm').value;
if (email != emailConfirm) {
alert("Email addresses are not the same.");
return false; //Returning 'false' will cancel form submission
} else {
/*
place the return true; at the end of the function if you do other
checking and just have if conditions and return them as false. If
one thing returns false the form submission is cancelled.
*/
return true;
}
}
</script>
And change your form to have onSubmit
<form method="post" action="submit_query.php" onSubmit="checkMatch()">
Add id's to your email inputs such as: email and emailConfirm. You can change them if you wish but just for an example I used those.
<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" onClick="javaScript:validate();" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.