This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I need to add to add the following characteristics to this form but I'm stuck. any help would b greatly appreciated. Thanks
One or more word characters
Exactly one at-sign
One or more word characters
Exactly one period Two or more characters that are a-z,
A-Z, 0-9, period, or hyphen
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
This function will work in your case
To call it like this
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
keep in mind that no 100% regex email check exists!
Checkout this link
https://stackoverflow.com/a/2855946/2630817
Try this:
<script>
function validateForm(){
var email=document.forms["myForm"]["email"].value;
var filter = /^(([^<>()[\]\\.,;:\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 (!filter.test(email)) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
</script>
Try this pure javascript:
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
Related
I am working on a mvc 5 project .in contact us page I want user to send admin his / her emaiul address .so I want to validate email in javascript on that page .I wrote some code that does not work properly. I want you to help me plesae.
<script language="javascript">
function f1() {
var inputText = document.getElementById("email").value;
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.value.match(mailformat)) {
document.form1.text1.focus();
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
<form name="form" action="#" onSubmit="return f1()" method="POST">
<input type="email">
</form>
<script>
function f1(){
var email = document.forms["form"]["Email"].value;
var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)#([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
if(!regex.test(email)){
alert("You have entered an invalid email address!");
return false;
}
}
</script>
You don't want inputText.value only inputText like this
<input type="text" id="email" />
<input type="submit" onClick="f1()"/>
<script language="javascript">
function f1() {
console.log(document.getElementById("email").value);
var inputText = document.getElementById("email").value;
console.log(inputText)
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.match(mailformat)) { // <<<<<<< here
//document.form1.text1.focus();
alert("correct")
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
A basic HTML and JS working code for validating email with JS is given here for u-
function validateForm()
{
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
{
alert("Valid e-mail address");
return true;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Think, u have your answer :)
function validateEmail(email) {
var re = ([\w-+]+(?:\.[\w-+]+)*#(?:[\w-]+\.)+[a-zA-Z]{2,7});
return re.test(email);
}
I have a form which lets the user to enter the email address twice. i need to validate that the email is like the regex and that the two emails match.
Something is wrong with my code. Please note that i am restricted to use javascript only. Thanks,
this is my javascript
function checkEmail(theForm) {
var re = /^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"+"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$/i;
if (theForm.EMAIL_1.value != re) {
alert('invalid email address');
return false;
} else if (theForm.EMAIL_1.value != theForm.EMAIL_2.value) {
alert('Those emails don\'t match!');
return false;
} else {
return true;
}
}
Your issue your not actually performing a regex. Your just comparing a regex string to an email.
if(theForm.EMAIL_1.value != re) /// <--- wrong.
{
alert('invalid email address');
return false;
}
On errors, use Event.preventDefault(); to prevent the form submit
Check for email validity only on the first input value
Than check to string equality on both input fields
function checkEmail (event) {
const e1 = this.EMAIL_1.value;
const e2 = this.EMAIL_2.value;
//Email Regex from //stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test( e1 );
const isMatch = e1 === e2;
if( !isEmail ){
event.preventDefault();
alert('Invalid email address');
}
else if ( !isMatch ){
event.preventDefault();
alert("Those emails don't match!");
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
Since you might have more forms where an email is required (Contact form, Login form, Newsletter form, etc etc...) for more modularity you could create a reusable function for validation and than a specific form submit handler separately:
/**
* #param {string} a Email address 1
* #param {string} b Email address 2
* #return {string} Error message
*/
function invalidEmails (a, b) {
a = a.trim();
b = b.trim();
if (!a || !b) return "Missing email";
// Email Regex from stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test(a);
const isMatch = a === b;
if (!isEmail) return "Invalid email";
else if (!isMatch) return "Emails do not match";
}
// Handle your form here
function formSubmitHandler (evt) {
const is_emails_invalid = invalidEmails(this.EMAIL_1.value, this.EMAIL_2.value);
if (is_emails_invalid) {
evt.preventDefault(); // Prevent form submit
alert(is_emails_invalid); // Show error message
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
You cant compare the first value with a regex. You have to use a regexp object. For more information read at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Try this below function to validate your email.
And after the validation, compare the 2nd email.
Please note that regex test method is used in the validateEmail method.
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
The below should work perfectly!
function validateForm(theForm) {
if (theForm.Email_1.value != theForm.Email_2.value)
{
alert('Emails don\'t match!');
return false;
} else {
return true;
}
}
How to validate a text box in html, where user will enter his first name, and input do not accept integers & Special Characters?
<input name="txtfname" type="text" maxlength="30" required />
Try this javascript code for validation
function Validate()
{
var val = document.getElementById('your_input_control_id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
return true;
}
You will want to check the username field on both the client and server side.
Javascript:
var username = document.getElementsByName("txtfname")[0].value;
if (username .match(/^[A-Za-z]+$/)) {
// Valid
} else {
// Invalid
}
PHP:
$username = $_POST['txtfname'];
if (preg_match("/^[A-Za-z]+$/", $username ) {
// Valid
} else {
// Invalid
}
In Javascript
var uname = document.form.username;
function validate(){
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
return false;
}
}
In Html
<form method="post" action="#" onSubmit="return validate();" name="form">
<input type="text" name="username" class="username"/>
<input type="submit" value="submit">
</form>
This is the proper RegEx.
The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. This RegEx will also work for names like André.
^[\p{L} .'-]+$
var username = document.getElementsById("fname").value;
if (username .match(/^[\p{L} \.'\-]+$/)) {
// Valid username
} else {
// Invalid username
}
I am trying to validate an e-mail address using javascript. The problem is the if statements aren't executing correctly. If I delete the 'else statement' the code runs correnctly and the page does not load with errors. If I include the 'else statement' the else statement never executes and the status bar says that the page loads with errors. I was wondering if anyone can find any errors that I am unable to pick up?
<h4>Example 4:</h4>
<div style="border:3px dashed #aaa; width:200px;">
<div id="text">e-mail: <input id="email" onblur="verifyEmail()"/></div>
<div id="verification" > </div>
</div>
<script type="text/javascript">
function verifyEmail(){
var email = document.getElementById("email").value;
var atPos=0;
var dotPos=0;
atPos = email.indexOf("#");
dotPos = email.lastIndexOf(".");
if(atPos<=3 || dotPos<atPos+2 || dotPos+2>=email.length){
document.getElementById("verification").innerHTML = "Invalid E-mail Address";
}else{
document.getElementById("verification").innerHTML = "Valid";
}
}
</script>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('emailaddress');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
Read more: http://www.marketingtechblog.com/javascript-regex-emailaddress/#ixzz1wqetPJQQ
try this
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);
}
Demo : Here is the demo
OR a more simpler way is
function validateEmail(email)
{
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
if you are using HTML5 try <input type="email"... please note. this one works if the input is in a form tag with a submit button and isn't handled by JS
<input type="email" placeholder="me#example.com">
The code below validate two nameserver textbox. As you can see there is redundancy in the javascript code. // validate textbox 1 and // validate textbox 2. Is there anyway I could just use one script.. you know I just want to use 1 validation function to validate two textbox. I'm sorry for my English I hope you all can understand me. Thank you.
<script type="text/javascript">
// validate textbox 1
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
// validate textbox 2
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver2.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver2').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver2').focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>
Well here is another approach:
function ValidateDomain(){
function CheckForBlank(domain, textBox){
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
}
function CheckForFormat(domain, textBox){
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
function GetDomainName(inputId){
var serverName = document.getElementById(inputId).value,
domain_array = serverName.split('.');
return domain_array[0];
}
var nameserver1 = GetDomainName('nameserver1'),
nameserver2 = GetDomainName('nameserver2'),
nameServerInput1 = document.getElementsById('nameserver1');
nameServerInput2 = document.getElementsById('nameserver2');
if (CheckForFormat(nameserver1,nameServerInput1) && CheckForBlank(nameserver1,nameServerInput1)
&& CheckForFormat(nameserver2,nameServerInput2) && CheckForBlank(nameserver2,nameServerInput2)){
//This means you are valid
return {
name1:nameserver1,
name2:nameserver2
}
}
return false;
}
Maybe like this:
<script type="text/javascript">
function validate_domain(){
validateTextBox('nameserver1');
validateTextBox('nameserver2');
}
function validateTextBox(tbName){
var nameserver1 = document.getElementById(tbName).value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(tbName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(tbName).focus();
return false;
}
}
}
</script>
Saw this one at work. Played with it at home. Here's a working jsFiddle. Yes, it's overly complex, but I detest alert('annoying pop-up');.
I commented the source, so you would better understand why I wrote it like that.
sg522: It may not copy/paste into your code and work, but I don't know what the rest of your code is. Neither are we here to write your code for you. We are here to help you learn and become a more experienced programmer.
Please let us know if you have questions.
Happy coding!
UPDATE: Modified jsFiddle to work with Opera and Firefox 10.
Neither Opera or Firefox apparently allow cloneNode to be called without parameters now.
Opera also apparently does not allow chained variable declarations.
Take the id of the element you want to validate as a parameter of your function.
// validate textbox
function validate_domain(serverName){
var server = document.getElementById(serverName).value;
var domain_array = server.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(serverName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(serverName).focus();
return false;
}
}
<script type="text/javascript">
// validate textbox
function validate_domain(ele){
var nameserver = ele.value;
var domain_array = nameserver.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
ele.focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
ele.focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(document.getElementById('nameserver1')); validate_domain(document.getElementById('nameserver2')); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>