I have an input form that I want to validate email adresses (or just an # sign). But I only want validation when it's wrong, so remove everything from before the else statement in the jquery snippet?
EDIT
When the user input is wrong, in this case not an emailadress, inform the user.
HTML
<form onsubmit="validate(); return false;">
<p>Enter an email address:</p>
<input id="email">
<button type="submit" id="validate">Validate!</button>
</form>
<br>
<h2 id="result"></h2>
jQuery
function validateEmail(email) {
var re = /#/;
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);
You can use not operator ! to reverse the condition like this:
function validate(){
$("#result").text("");
var email = $("#email").val();
if (!validateEmail(email)) { //email is invalid?
$("#result").text(email + "is not valid :(");
$("#result").css("color", "red");
//call a function to trigger
return false;
}
}
Related
To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)
I am putting validation on email field but it shows error of invalid even where the email is typed in correct format.
Screenshot
Code
<script type="text/javascript">
function formvalidate(){
var email=document.signup_form.email.value;
var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$");
if(email=="")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
</script>
Thanks
try this function
function validateEmail(elementValue) {
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
Please refer this fiddle : http://jsfiddle.net/gabrieleromanato/Ra85j/
1- Use this regular expressions instead
\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
2- Change this if (!check_email.test(email)) to
if (check_email.test(email))
Try this fuction
function isEmail(inputString) {
var regExpEmail = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
try {
return regExpEmail.test(inputString.value);
}
catch (e) {
return false;
}
}
Change var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$"); to
a function like 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);
}
You regex is not correct, there are many things that you've not considered, like your regex accepts only capital letters, to include both capital and small letters you should use :
[a-zA-Z0-9]
not this :
[A-Z0-9]
You can use this regex for validating email :
/^(([^<>()\[\]\\.,;:\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,}))$/
read this for details
Source and some tests
You can use this regex for email:
RegExp('\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b', 'i')
try this example : email validation using JQuery
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() {
$("#emailvalidate").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#emailvalidate").text(email + " is valid");
$("#emailvalidate").css("color", "green");
} else {
$("#emailvalidate").text(email + " is not valid");
$("#emailvalidate").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='submit' id='btn'>Validate</button>
</form>
<h2 id='emailvalidate'></h2>
Try this code -
function formvalidate()
{
var email = document.signup_form.email.value;
var check_email = RegExp("^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$", 'ig');
if(email == "")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
<form name="signup_form">
<input type="text" name="email" value="" />
<input type="button" name="validate" value="Validate" onclick="formvalidate()"/>
</form>
I am using below regex to validate email pattern. Regex is not 100% solution to validate an email, better use email verification. Regex can help to validate format or pattern only.
Jsfiddle: DEMO
Jsfiddle: Regex check and sample email DEMO
function validateEmail(elementValue) {
document.getElementById('error').innerHTML = elementValue + ', email is incorrect';
var emailPattern = /^[a-z0-9](?:[a-z0-9]+\.)*(?!.*(?:__|\\.\\.))[a-z0-9_]+#(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9](?!$)){0,61}[a-zA-Z0-9]?)|(?:(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])))$/;
if (emailPattern.test(elementValue)) {
document.getElementById('error').innerHTML = elementValue + ', email is correct';
}
return false;
}
#error {
color: red;
font-size: 2rem;
}
input[type='email'] {
padding: 5px;
width: 300px;
border-color: blue;
font-size: 16px;
}
<form name="signup_form">
<input type="email" value="" onblur="validateEmail(this.value)">
<br />
<lable id="error"></lable>
</form>
Change your regular expression to below
^[a-zA-Z0-9._-]+#[A-Za-z0-9.-]+\.[a-zA-Z0-9.-]+$
Hope this helps :)
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'm using javascript to validate my html (checking if the user input a correct data ) source code and it's more than simple but the problem is that when i press the submit button i can't see any result or alert
<script type= "text/javascript">
function checkname()
{
name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
return name.value("Welcome" + name + " to valet parking service VPS");
}
</script>
that's all for the first part where the script is written now in the html tag where the button is typed
<input type="submit" value=" submit " >
and that's what written in the form
<form onsubmit = " checkname(); return false; ">
This is the mistake (you always return false to the submit function):
<form onsubmit = " checkname(); return false; ">
Try this:
<form onsubmit="return checkname();">
Then modify your checkname function to something like this:
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
name.value("Welcome" + name + " to valet parking service VPS");
return true;
}
Here is the JSFiddle: http://jsfiddle.net/267wL/
HTML
<form action="demo.html" id="myForm" onsubmit = "checkname(); return false; " method="post">
<p>
<label>First name:</label>
<input type="text" id="myname" />
</p>
<input type="submit" value=" submit "/>
</form>
JavaScript
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/;
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
name.value = "Welcome " + name.value + " to valet parking service VPS";
return false;
}
You don't have to check null values. If the name.value is empty, your regex validation failed.
Pay also attention that the welcome message is set in the input text. Weird behaviour...
The return true; will block all following code.
Try This
<script> function checkname() {
var x = document.forms["myForm"]["myname"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
<form name='myForm' action='action.php' onsubmit='return checkname()' method='post'>
First name: <input type="text" name="myname"><input type="submit" value="Submit"></form>
I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}