Really basic, I'm just trying to understand how to test a form using simple JavaScript without jQuery etc. Tried W3Schools but didn't work.
So I'm trying just a simple form instead with one field to get how it all works. Below I put a single field in a form, and thought I could test the fname variable against the firstName field.
But what happens is that the alert is never hit in the if statement. How to test the field firstName?
Any tips would be helpful.
function validateForm() {
var fname = document.getElementById("firstName");
if (fname == "") {
alert("first name is a mandatory field");
} else {
document.getElementById("formMessage").innerHTML = fname + " entered.";
}
}
<h2>Question 1 validate with alert popups</h2>
<p>Please enter the following mandatory information</p>
<form name="identification">
<p>First Name:<input type="text" id="firstName" /></p>
<p>
<button type="button" onclick="validateForm()">Submit</button>
</p>
</form>
<p id="formMessage"></p>
You're comparing the element itself. You should instead check the value of the element.
e.g.
var fname = document.getElementById("firstName").value;
fname is the element when you do document.getElementById, so you have to do:
function validateForm() {
var fname = document.getElementById("firstName");
if (fname.value == "") {
alert("first name is a mandatory field");
} else {
document.getElementById("formMessage").innerHTML = fname.value + " entered.";
}
}
You might also want to trim fname.value in case the user inputs bunch of empty spaces.
Use document.getElementById("firstName").value to get the value. if you don't add .value it means it didn't read the specified value.
Related
I am writing three functions in javascript to do different things. Search functions only needs firstname and lastname. Add and update functions needs everything to filled out completely. I have those working, however when submitting form, if anything is missing, it alerts me but still submits it. I don't want it to do that, how can i do it?
function search() {
checkme = false
//alert('all feilds must be filled out');
var nameExpression = /^[a-zA-Z]+$/;
firstName = document.getElementById('firstName').value;
lastName = document.getElementById('lastName').value;
//check firstname
if (firstName!=""&&nameExpression.test(firstName)) {
checkme = true;
}else{
document.getElementById("firstName").classList.add("is-invalid");
alert("Please enter valid first name");
}
//check lastName
if (lastName!=""&&nameExpression.test(lastName)) {
checkme = true;
}else{
document.getElementById("lastName").classList.add("is-invalid");
alert("Please enter valid last name");
}
return checkme;
}
, here is how i am calling the function as well
<input name="Action" type="submit" name="Search" value="Search" onclick="return search();"">
The reason your function fails to stop submission, is because of a system called event bubbling, where an event propagates up the DOM tree, and any handlers related to that event are triggered. There are also default events that occur on certain actions. Some of these are cancelable events, one of which is the Form Submit event. The e.preventDefault() command basically cancels the default action of the event, which is submitting the form, and prevents it from submitting regardless of the output of your function. We then call the submit() function manually when all requirements are satisfied.
Here's a version that I feel is shorter and easier to understand. No checkme variables needed either. It assumes your form has the id yourForm, and submits it if both first and last names pass the RegEx check.
function search(e) {
e.preventDefault();
const nameExpression = /^[a-zA-Z]+$/;
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;
const yourForm = document.getElementById('yourForm');
if (nameExpression.test(firstName) && nameExpression.test(lastName)) {
yourForm.submit();
} else {
alert('All fields must be filled out, and contain only alphabets');
}
}
document.getElementById('yourForm').addEventListener('submit', search);
<form id="yourForm">
<input type="text" id="firstName" placeholder="First Name" />
<br>
<input type="text" id="lastName" placeholder="Last Name" />
<br>
<input name="Action" type="submit" name="Search" value="Search">
</form>
P.S. You can do what you are trying to do here in pure HTML by adding the pattern attribute to your first and last name inputs. This also helps in case the user has an extension like NoScript installed, but the downside is you cannot control how the validation error looks.
(I'm beginner/intermediate in JS) I once also worked on something like this. I would suggest to add a paramater of 'e' in your function, en then writing "e.preventDefault" In your code. It would prevent the default submit action of your form. And then, you can submit the form in JS if it matches a certain condition, and if not, it will give you an alert.
Im guessing checkme, firstName and lastName weren't defined yet.
function search(e) {
e.preventDefault();
var checkme = false;
//alert('all fields must be filled out');
var nameExpression = /^[a-zA-Z]+$/;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
//check firstname
if (firstName!=""&&nameExpression.test(firstName)) {
checkme = true;
} else {
document.getElementById("firstName").classList.add("is-invalid");
alert("Please enter valid first name");
}
//check lastName
if (lastName!=""&&nameExpression.test(lastName)) {
checkme = true;
} else {
document.getElementById("lastName").classList.add("is-invalid");
alert("Please enter valid last name");
}
if (checkme == true) {
your_form.submit();
}
This may not be a perfect solution to your problem, but this is roughly how I do these things with JS and validating forms. I hope this helped.
Edit:
The code is the author's source code, I tried to not edit it too much.
NOTE:
Same email id can't be repeated.
The empty string value can be allowed to add.
Email Id should separated by ; and ,.
Basic emailId validation is required for entered email id
[![
$("#d-notification").focusout(function () {
var conditions = [".com", ".in", "#"];
var d = document.getElementById("d-notification").value;
var res = conditions.some(el => d.includes(el));
if (d !== "" && res === false) {
document.getElementById("error-d").style.display = "block";
$("#generate-dispatcher").attr("disabled", true);
} else {
document.getElementById("error-d").style.display = "none";
$("#generate-dispatcher").attr("disabled", false);
}
});
#error-d {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea type="text" id="d-notification" class="form__field resize"
placeholder="Enter the Email Id"></textarea>
<span id="error-d" class="error-noti">Please Enter valid Email Id</span>
</div>
]1]1
I think you have two choices.
One could be that you set up a control that is a div with a textarea and when you enter an email and then a ";" or a "," it creates a new tag with javascript that can be a div or a span that shows the email to separate it into different items and then validate each of them.
The other could be that when you do the validation as you do now, you make a split of emails by ";" or "," and then validate each email in that array of result.
Good luck
Matias Creimerman
I've been trying to compare two inputs.
First input is type "hidden" and get value from database.
For second input - value insert customer, but only if is same as in database, can her update his data.
Here is php:
<input id="pass1" type="hidden" value= "'.$row_pswd['pswd'].'" />
<input id="pass2" type="password" placeholder="password" required />
and script:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").<?php echo SHA1("value"."t&#sdhstöksdf54gh"); ?>;
var ok = true;
if (pass1 != pass2) {
alert("Passwords Do not match");
document.getElementById("pass2").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
</script>
Any help would be much appreciated.
I don`t think its a good idea to do that in Javascript. You kinda giving the way user password this way. Also hidden field with the password as value? Not good!
Move all this into php. Make the person first write the password, compare it in php and than update the info. If you want to do it in one page, use ajax.
I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">
I have been trying form validation in javascript and html. I am stuck with the use of onblur(). The idea is that the user enters his name. If he moves out of the input area (textbox) without entering anything, then error message should be shown.
But according to my code below even if I enter anything, it still shows alert no name entered.
<form>
<input type="text" id="fn" value="First Name" onfocus="fnm()" onblur="chfnm()"/>
</form>
function fnm()
{
document.getElementById("fn").value=""; //clears default value of textbox
}
function chfnm()
{
var f=document.getElementById("fn");
for(var i=0;i<f.length;i++)
{
if(i!=(f.length-1))
fname= fname +f.elements[i].value +"<br>";
else
fname= fname+ f.elements[i].value;
}
if(fname=="") //error is fname is always an empty string
{
alert("Please fill your first name");
document.getElementById("fn").focus();
}
}
I am new to javascript so any new ideas are appreciated and welcome.
If you want to do validate that user inputting the name or not, you can simply use this code. If so you are putting extra code with for loop.
function fnm(){
document.getElementById("fn").value=""; //clears default value of textbox
}
var fname = "";
function chfnm(){
fname = document.getElementById("fn").value;
if(fname==""){
alert("Please fill your first name");
document.getElementById("fn").focus();
}else{
alert("your name " + fname);
}
}
DEMO
Just add required tag of html5 so no need to add extra java script function for checking