This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 9 months ago.
Referring to this issue:
How can I set a minimum length for a field with jQuery?,
<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>
What would the code be for settting a minimum length for a field with jQuery?
$('#new_invitation').submit(function(event) {
if ($('#invitation_form_recipients input').filter(function() {
return $(this).val();
}).length == 0) {
// All the fields are empty
// Show error message here
// This blocks the form from submitting
event.preventDefault();
}
});
How can I validate that every field input have a valid email address with jQuery? In the above code?
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
Email: {
group: '.col-sm-3',
enabled: false,
validators: {
//emailAddress: {
// message: 'Email not Valid'
//},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'Email not Valid'
},
}
},
This : /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i is not working for below Gmail case
gmail.#gmail.com
gmail#.gmail.com
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
Regex Solution link
/(?:((?:[\w-]+(?:\.[\w-]+)*)#(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
This :
var email = /^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
function mailValidation(val) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(val)) {
$('#errEmail').text('Please enter valid email.');
}
else {
$('#errEmail').hide();
}
}
Related
I am trying to give a textfield a dual function. So, if you type, say, 12345, into it, it finds the relevant data. But if you type an email-address, or essentially anything with an XXX#XXX.XXX format, I want the password-field and button to appear. I've been trying to use regex, but for some reason it does not work, and everything is recognised as an email, so even 12345 opens the login-things. Can you help me? I've tried getting the gist into the snippets.
function imgMain() {
var iDCode = document.getElementById("IDQuery").value;
var mail = /^[a-zA-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])?)*$/;
if (iDCode = mail) {
console.log("this is a mail");
document.getElementById("passwordDiv").style.display = "block";
document.getElementById("loginbuttonDiv").style.display = "block";
document.getElementById("SeeSlide").style.display = "none";
} else {
console.log("this is not a mail")
}
}
<div id="QueryField">
<input type="text" id="IDQuery" placeholder="ID Kode">
<div style="display: none" id=passwordDiv><input type="password" id="passwordfield"><br></div>
<div style="display: none" id=loginbuttonDiv><button id="login" onclick="login()">log ind</button><br></div>
<button id="SeeSlide" onclick="imgMain()">Se Slide</button><br>
<br><br><br><br>
</div>
user mail.test() with proper regex like so
let mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mail.test(iDCode)){
alert("Valid email is required")
}
You can try this version, it's based on the w3resource.
function imgMain() {
var iDCode = document.getElementById("IDQuery").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (iDCode.match(mailformat)) {
console.log("this is a mail");
document.getElementById("passwordDiv").style.display = "block";
document.getElementById("loginbuttonDiv").style.display = "block";
document.getElementById("SeeSlide").style.display = "none";
} else {
console.log("this is not a mail")
}
}
<div id="QueryField">
<input type="text" id="IDQuery" placeholder="ID Kode">
<div style="display: none" id=passwordDiv><input type="password" id="passwordfield"><br></div>
<div style="display: none" id=loginbuttonDiv><button id="login" onclick="login()">log ind</button><br></div>
<button id="SeeSlide" onclick="imgMain()">Se Slide</button><br>
<br><br><br><br>
</div>
In your if statement you have if (iDCode = mail).
This re-assigns the value of mail to the variable iDCode. So the if effectively becomes if(mail) which is always true, because RegEx objects are truthy.
You should instead be checking if the input matches the regex, using either mail.test(iDCode) or iDCode.match(mail)
Few different ways. You can send an email to that address and check whether it bounces back or you can use PHP (I doubt you want to do this since your question is JavaScript) and send an email and then have them confirm it on the web address. Honestly, PHP is the best way to do this but since you're using JS you can try this from https://www.w3resource.com/javascript/form/email-validation.php:
function ValidateEmail(mail) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value)) {
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
This works because we are checking all the invalid characters that are in an email address. If the input field contains any of those characters, its invalid.
Try Googling the answer. There are lots of information:
https://www.google.com/search?rlz=1C1GCEB_enUS865US865&ei=bn9dXuefDanJ0PEPofOHyAg&q=javacsript+check+email+address&oq=javacsript+check+email+address&gs_l=psy-ab.3..0i71l8.2549.3358..3533...0.2..0.0.0.......12....1..gws-wiz.........23%3A11-12j24%3A11-2.1hEMZpGGmWs&ved=0ahUKEwjnjr7N4vznAhWpJDQIHaH5AYkQ4dUDCAw&uact=5&safe=active&ssui=on
You can try using the .validate function. It works really great for checking login forms.
The function could look like the following:
$("#IDQuery").validate({
rules: {
email:
{required: true, email: true},
password:
{required: true}
},
messages: {
email:
{required: 'Please enter a E-mail',
email: 'Please enter a valid E-mail'},
password:{required: 'Please enter a password'}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
This question already has answers here:
jQuery Validate, need to prevent free email addresses (e.g. Gmail, Hotmail)
(3 answers)
Jquery validation for email address or domain name
(2 answers)
override jquery validate plugin email address validation
(4 answers)
Validate Format of an Email Address using Jquery.validate.js [closed]
(1 answer)
Closed 5 years ago.
I have an HTML form that contains an input which requests a users email address. There are several email addresses that if entered should not allow the form to submit e.g. #donotsubmit.com, #donot.submit.com.
Using jQuery, is it possible to prevent the form from submitting if the input contains these strings? The code looks like this:
<input class="form-control emailrequired" id="Email" name="Email" placeholder="Email" type="text" value="" />
<script type="text/javascript">
$().ready(function () {
$.validator.addMethod("cRequired", $.validator.methods.required, "Please ensure this field is complete");
$.validator.addClassRules("emailrequired", { cRequired: true, email: true });
});
</script>
Edit:
Updated script using jQuery Array. The issue I am having is that the jQuery Validate is not using the inArray statement to mark the field as valid/invalid.
<input class="form-control emailrequired" id="Email" name="Email" placeholder="Email" type="text" value="" />
<script type="text/javascript">
$().ready(function() {
$.validator.addMethod("cRequired", $.validator.methods.required, "Please ensure this field is complete");
$.validator.addMethod("domain", function(value, element) {
var emailAddress = $('#Email').val();
var emailDomain = emailAddress.substr(emailAddress.search('#') + 1);
var invalidAddresses = ["donotsubmit.co.uk"];
if (jQuery.inArray(emailDomain, invalidAddresses) !== -1) {
event.preventDefault();
}
}, "Please use a personal email account");
$.validator.addClassRules("emailrequired", {cRequired: true, email: true, domain: true});
});
</script>
So in my registration form I have this field:
<div class="form-group">
<label for="RegisterModel_Password">Password</label>
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password" class="form-control"
required="required" minlength="8"/>
</div>
As you see, I'm using jQuery validation attributes to ensure that the password includes at least 8 characters. So, I want to check if password contains uppercase and number, if not, field is not valid. I downloaded additional method for jQuery Validation plugin named "pattern" and added her in head tag.
I tried to do this as follows but it didn't worked.
$("#formRegister").validate({
rules: {
RegisterModel_Password: {
pattern: /^[a-zA-Z][0-9]/
}
}
});
I assume that the pattern is wrong, but I'm not sure whether the use is correct.
Thank you for your help.
Chains of regular expressions are too hard for me ( I have never tried to learn them lol ). So here is my solution:
jQuery.validator.addMethod("passwordCheck",
function(value, element, param) {
if (this.optional(element)) {
return true;
} else if (!/[A-Z]/.test(value)) {
return false;
} else if (!/[a-z]/.test(value)) {
return false;
} else if (!/[0-9]/.test(value)) {
return false;
}
return true;
},
"error msg here");
And simply I use it like a attribute:
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password"
class="form-control"
required="required" minlength="8"
passwordCheck="passwordCheck"/>
Thanks for your answers.
You can add your custom validation using $.validator.addMethod() like:
$.validator.addMethod("validation_name", function(value) {
// at least 1 number and at least 1 character
[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
});
I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.
I am trying to create a form where people can add their email addresses to sign up to a mailing list. I am struggling to validate whether they actually entered an e-mail address or not with JavaScript.
Here is the HTML form:
<script type="text/javascript" src="validate-email.js"></script>
<form id="updateform" action='send.php' onsubmit="return validateForm();" method='post'>
<input type="email" name="emailaddress" placeholder="Your e-mail address"/>
<input type="submit" name="submit" value="Submit">
</form>
And here is the JavaScript file's contents:
function validateForm()
{
var x=document.forms["updateform"]["emailaddress"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address to receive updates.");
return false;
}
}
What am I doing wrong? I am a complete beginner...
EDIT: Why is this down-voted? What did I do wrong? If you read my comments, this is a legitimate problem, and the solutions I searched on Stack Overflow do not meet my needs.
1) use jQuery or similar framework and plugins.
2) use type="email" attribute for input tag.
<input type="email" name="email">
Or validate custom:
// validate function
var isEmail = function(email){
return /^((([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])))$/.test(email);
}
function validateForm(){
var email;
// ...
// get value from html stuff
// ...
if(!isEmail(email))
return alert('Email format fail! Please correct.')
// do something next...
// alert("That's it! Dude.");
}
Use the regular expression to validate the email.
use this regex to validate
var regex= '/^(([^<>()[\]\\.,;:\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,}))$/';
Original Post is here
Edit!
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 validateForm()
{
var email=document.forms["updateform"]["emailaddress"].value;
if (!validateEmail(email))
{
alert("Please enter a valid e-mail address to receive updates.");
return false;
}
}