Validating email client side [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
How do I validate email on the client side using javascript when the server side cannot validate? From my understanding Javascript can be turned off so how can this be achieved and prevent me from receiving PCI warnings?
$(document).ready(function() {
var clearMePrevious = "";
// clear input on focus
$("#email").focus(function() {
if($(this).val()==$(this).attr("title")) {
clearMePrevious = $(this).val();
$(this).val("");
}
});
// if field is empty afterward, add text again
$("#email").blur(function() {
if($(this).val()=="") {
$(this).val(clearMePrevious);
}
});
$('#submitemail').click(function() {
app.ajax.load({
reqName : 'emailSubmit',
url: '$httpUrl('Bronto-OptIn')$?email=' + $('#email').val(),
selector : '#emailbox',
callback: function(responseText, textStatus) { }
});
return false;
});
});
<form id="emailsignup_form" name="emailsignup_form" method="post" action="$httpUrl('Bronto-OptIn', 'fid', 'information')$">
<div class="fl"><input class="email-signup-input" type="text" title="Enter Your Email Address" value="Enter Your Email Address" name="email" id="email" /></div>
<div class="fl"><button class="email-signup-btn" value="Submit" name="submitemail" id="submitemail">Submit</button></div>
<div class="clear"> </div>

If client side validation is necessary I would put in a fallback for the case that javascript is not enabled -
<script type="javascript">
/* Wire up form submittal */
</script>
<noscript>
<p>JavaScript is required to use this form, please enable JavaScript in your browser!</p>
</noscript>
See this -
How to detect if JavaScript is disabled?

Related

Issues with JavaScript window.location.href [duplicate]

This question already has answers here:
window.location.href not working
(4 answers)
Closed 1 year ago.
So I have been working on this little puzzle site and I want the correct password for the textfield to be inside the JS function. Now it does recognize the password already which is good but the issue is that when I try to use window.location.href = "https://www.google.com"; it does not redirect the page to new site. It only "refreshes" the site..
My script is as followed:
<script>
function validate() {
var password = document.forms["passwordform"]["password1"].value;
var realpassword = 'salaisuus'
if (password === realpassword) {
window.location.href = "http://www.google.com";
return true;
} else {
alert("Wrong password")
return false;
}
}
</script>
and the actual form is here:
<form id="passwordform" onSubmit="return validate()">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput" name="password1" placeholder="whatwhat">
<label for="floatingInput">PASSWORD</label>
</div>
<button type="submit" class="btn btn-dark">TRY IT</button>
</form>
So as said, it does send the alert for wrong password, but the window.location.href is not working. What am I missing here?
www.stackoverflow.com/q/15759020/14834893 here is the answer of your question. – M.Hassan Nasir
Okey, so being little dummy...
All I need to do is add return false; after window.location.href
Thank you

Email validation with jQuery, noobish problem [duplicate]

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();
}
}

Do not submit form if input string contains certain value [duplicate]

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>

Regex email validation on submit

I want to do a very basic jQuery validation of an email via a regex on submit. My HTML:
<form action="POST" id="form">
<input type="email" id="customer_email" placeholder="email here" />
<input type="submit" />
</form>
JS:
$('#form').submit(function() {
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').value();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
To my understanding, for this to work I need to get the value of the input via email input (which I do on line 4) and run a regex on it.
When submit is clicked, the standard input error appears on the form, and not the window alert. Feel free to view a Codepen outlining this here:
http://codepen.io/anon/pen/oYmJLW?editors=1010
You need to add event.preventDefault() to prevent the actual form submission, and use .val() instead of .value() on the input.
$('#form').submit(function(event) {
event.preventDefault();
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').val();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
By declaring your input as type="email" your browser will do the validity checking (you don't need to do it yourself then), if you want to circumvent that use type="text".

How to store a flag in a cookie where the flag is true only if a form has been completed?

How to store a flag in a cookie where the flag is true only if a form has been completed?
I have a sidebar contains a form, which when successfully submitted fades the form and display a message using one of the user inputs.
This sidebar form is present over a number of pages on the website. In order to identify if the form has already been completed on another page I believe I can use a flag variable to define whether this is true or false and then display the form or the message depending on the stored value.
I have never used cookies as a medium to store a value and do not know the correct syntax for them. Can I simply make the cookie when the formsubmit is successful. And on every page have a script in the header that will then be read to either display the form or not.
Is this the best way to go about this? And what is the format and correct syntax to identify something like this?
HTML
<div id="sidebarf">
<form id="sidebarform" onsubmit="return false" method="post" name="myForm" autocomplete="off" >
<input type="text" name="name" id="username" placeholder="Name (eg. Rob James)" value="" required><br><br>
<input type="text" name="location" id="userlocation" placeholder="Location (eg. Wacol)" value="" required><br><br>
<input type="text" name="postcode" id="userpc" pattern="[0-9]{4}" placeholder="Postcode (eg. 4076)" maxlength="4" value="" required> <br><br>
<input type="email" name="email" id="useremail" placeholder="Email Address (eg. someone#yourdomain.com" value="" required> <br><br>
<input type="tel" name="phone" id="userphone" placeholder="Phone Number (eg. 0412345678)" maxlength="10" minlength="6" value="" required> <br><br>
<textarea rows="4" cols="20" id="usercomment" placeholder="Comment/Question" value="" required></textarea><br><br>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
JAVASCRIPT
$("#sidebarform").on("submit", function() {
if ($("#username").val() == "") {
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("Thankyou for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
});
return false;
/////////////////Is this the flag?/Correct Location?//////////////
//////var completed = true
//////document.cookie=completed;
///////////
});
</script>
And then would I call something like this when the page loads?
///////////////////DOES NOT WORK/////////////////
<script>
function checkCookie()
{
var display=getCookie("completed");
if (complete!="true")
{
$("#sidebarf").html("Thankyou for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
}
else
{
$("#sidebarf").html //(Don't know what to put here!)
}
}
I also have this for a custom validity after the above code. But this shouldn't play a role.
$(document).ready(function () {
$('#username').on({
invalid: function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter a name.");
}
},
input: function(e) {
e.target.setCustomValidity("");
}
});
As I said, I honestly have no idea about the cookie use so the code is just what I've search on the web.
If you use this jQuery cookie plugin you can simplify your code a great deal. The following code should check for the cookie when the page loads. If the cookie is found, the form is immediately hidden without animation. Otherwise when the form is submitted, the cookie is set so that at the next page load the form will be hidden.
$(function() {
var completed = $.cookie( 'completed' ),
form = $('#sidebarform'),
msg = $('#sidebarf');
if( ( completed != undefined ) && ( completed == 'done' ) ) {
form.hide();
msg.html( 'Form already completed.' );
}
form.on("submit", function( e ) {
e.preventDefault();
if ( $("#username").val() == "" ) {
return false;
}
$(this).fadeOut("slow", function() {
msg.html("Thank you for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
form.submit();
//or submit form via ajax ---> YOUR CHOICE
$.cookie( 'completed', 'done' );
});
});
});
JS FIDDLE DEMO

Categories