Validating an e-mail address using regex - javascript

I am trying to validate e-mail addresses on my website and I have been trying to code up a demo of how e-mail validation would work with JavaScript. What I am trying to do is pass in the value of the e-mail address entered by the user to the validateEmail function and then print out 'valid' or 'invalid' in the div with the id 'result'. Because I am relatively new to JavaScript, I am not sure how to accomplish this and was wondering it if someone could show me an example of how to do this?
<head>
<title>Practice</title>
<script type="text/javascript">
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>
</head>
<body>
<form action="post" method="practice.php">
e-mail: <input id="email" type="text" onblur="validateEmail(execute(document.getElementById('email').value))" />
<div id="result"></div>
</form>
</body>

First of all you don't need to use execute method and can get value from this context:
validateEmail( this.value )
Then modify your function to print result:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(email)) {
document.getElementById('result').innerHTML = 'valid';
} else {
document.getElementById('result').innerHTML = 'invalid';
}
}

Related

JS Student Email Validation

I am a beginner in Javascript and am looking to find a solution to why the code below is not working.
I've reviewed several tutorials here on StackOverflow and believe it should work... but it's not.
The HTML looks like this:
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
<br>
</form>
<input type="button" onclick = "validateEmail()">
The Javascript looks like this:
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms[personalInfo].elements[Email].value;
if (reg.test(address) == false) {
alert ("Email not valid");
return false;
}
return true;
}
By my accounts, this should pop up an alert if the email address entered by the user is not valid.
Instead, nothing happens at all. I'm not sure if the test is even run.
function validateEmail() {
// There are, I feel, better version of this regex online
// You can check "https://emailregex.com/"
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
// document.getElementById() - Easier to read & understand, and more widely used
var address = document.getElementById('Email').value;
// Corrected your returns - not the main issue in the function, but the old
// returns might have caused confusion
if (reg.test(address) == false) {
alert("Email not valid");
return false
}
return true
}
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
</form>
<!-- You had a typo on the onclick but has since been fixed -->
<input type="button" onclick="validateEmail()" value="Submit">
Two issues here:
1- In your HTML, you are missing an = sign here: onclick"validateEmail()" (Edit: seems you fixed it now)
2- in your Javascript, the indices personalInfo and Email are strings, wrap them in quotation marks:
var address = document.forms['personalInfo'].elements['Email'].value;
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms['personalInfo'].elements['Email'].value;
if (reg.test(address)== false)
{
alert ("Email not valid");
return false
}
return true;
}
<form id="personalInfo">
<h2>Email: </h2> <input type="text" name="Email" id="Email"> <br>
</form>
<input type="button" onclick="validateEmail()">
When dealing with email inputs, set the input type to email instead of text - like so:
<input name="my-email" type="email" />"
Then the browser will perform validation on the input; such as if the input doesn't have the # present.

Javascript form validating and prevent submission

How can I prevent submision if in my text field are entered just specific characters <>{} and not all of special characters? I'm losing my mind :/
I think you are looking for regex expression. Let me know if it's helpful
$(":input").each(function() {
var input = $(this).val();
var regex = new RegExp("^[a-zA-Z]+$");
if(regex.test(input)) {
alert("true");
} else {
alert("false");
return false;
}
})
I don't have an exact answer as you didn't post any sample code. I can only point you to this article https://javascript.info/bubbling-and-capturing which explain how events bubbling works. A solution will be to use event.stopPropagation() in case the validation doesn't pass.
Here an working ex:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
const regex = new RegExp('^[a-zA-Z]+$');
const input = document.forms['someForm']['somename'].value;
if (regex.test(input)) {
console.log("true");
} else {
console.log("false");
return false;
}
}
</script>
</head>
<body>
<form name="someForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="somename">
<input type="submit" value="Submit">
</form>
</body>
</html>

Javascript live validation

I have a very simple HTML/JavaScript form that I am working on for coursework, I have got it to work however i would like it to validate the input as the user types (my validation appears below the text field) how can I achieve this? My code is as follows:
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http:ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<meta charset=utf-8 />
<title>Email Validation</title>
</head>
<body>
<form onsubmit='validate(); return false;'>
<p>Enter an email address:</p>
<input id='email' placeholder="example#example.com" size="21">
<button type='submit' id='validate'>Submit</button>
</form>
<br />
<h2 id='result'></h2>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
$("#result").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#result").text(email + " is valid");
$("#result").css("color", "green");
} else {
$("#result").text(email + " is not valid");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
</script>
</body>
</html>
For methods not using jQuery, in case you're interested, there's another Stack Overflow question here: On Input Change Event.
There are many ways to do what you want listed there, but in this case you could do something like this:
var input = document.querySelector('input');
input.addEventListener('input', function()
{
// Check input.value for what you're looking for here
});
See the jsFiddle that Drew Noakes' made in that other page for an example.
But, since you're using jQuery, then Nicholas Kyriakides's suggestion is the way to go.

JavaScript Is Text Box Empty?

How can I check if a input field is empty in JavaScript when submitting the form?
html:
<input type="text" name="start_name" id="start_name">
Refer to http://www.w3schools.com/js/js_form_validation.asp
Have your form tag as
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Next, have a javascript function
<script>
function validateForm()
{
var x=document.forms["myForm"]["start_name"].value;
if (x==null || x=="")
{
alert("Start name must be filled out");
return false;
}
}
</script>
var start_name = document.getElementById('start_name');
if( start_name.value.length > 0 ){
// Then there is something there.
}
Try.
<script type="text/javascript">
function checkme()
{
var inputVal = document.getElementById("start_name").value;
if(inputVal == "")
{
//code
}
}
</script>
<form action="" method="post" onSubmit = "checkme();">
<input type="text" name="start_name" id="start_name">
</form>
Just checking 'if (x==null || x=="")' is not enough to validate empty text box. Go for RegEx to check empty text box.
/^\s*[0-9a-zA-Z][0-9a-zA-Z ]*$/
Ensures that at least one character is not whitespace and is of one of the allowed characters.
Use /[a-z]/i as this regex will only match if there is at least one alphabetical character.
<form action="someActionUrl" onsubmit="return validate('first_name')">
<input id="first_name" name="first_name" />
</form>
<script>
function validate(inputId){
var val = document.getElementById(inputId).value;
if(val.length>0){
// do something
return true;
}
return false;
}
</script>
try this:
var x = document.getElementById("start_name");
if(x.value== "")
{
//your restriction code comes here
}
else
{
//go ahead!
}
Note: please check for syntax if its proper.i am writing the code here directly,haven't checked it on IDE.

Having issue to validate form using JavaScript

My following JavaScript is not working:
<script type="text/javascript">
function checkDetails(search)
{
var search = documment.getElementById('query');
if(search.value ==''||search.value==null)
{
alert('No search criteria entered');
query.focus;
return false;
}
}
</script>
</head>
<body>
<form name="search" action ="123.php" onSubmit="return checkDetails(this);" method ="get">
<p><input type ="text" id = "query" name ="query" />
<input type ="submit" value ="Web Service"/></p>
</form>
</body>
Try this code:
function checkDetails(search)
{
var search = document.getElementById('query');
if(search.value ===''||search.value===null)
{
alert('No search criteria entered');
search.focus();
return false;
}
return true;
}
You wrote documment.
You don't specify in what way it's not working - you get an error, it doesn't validate correctly, you don't get the error alert? One thing I spotted:
query.focus;
Should be
search.focus();
Also you misspelled document as documment
Also try something like this
onSubmit="return checkDetails(this,this.id);"
function checkDetails(search,id)
{
var search = documment.getElementById(id);
if(search.value ==''||search.value==null)
{
alert('No search criteria entered');
query.focus;
return false;
}
}
It will be
search.focus();
instead of
query.focus;
and documment will be document

Categories

Resources