Allow edu domain emails in form jquery - javascript

I tried various solutions but it didn't work. Not that good with JavaScript especially with RegEx.
Found this solution online, but couldn't modify it.
Basically I need to allow EDU domain in email field. I think it would be #ohio.edu or #ohio.edu.com or something like that. How can I say that if there isn't phrase "edu" after #, then don't allow the registration?
$(".single-memberpressproduct.postid-1945 .mepr-submit").click(function() {
validateEmail(jQuery("input#user_email1").val());
return false;
});
function validateEmail(email) {
var emailRegx = /b(?:(?![_.-])(?!.*[_.-]{2})[a-z0-9_.-]+(?<![_.-]))#(?:(?!-)(?!.*--)[a-z0-9-]+(?<!-).)*.edub/i;
if (emailRegx.test(email)) {
if (email.indexOf('#edu.com', email.length - '#edu.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Not a valid e-mail address #.');
}
} else {
alert('Not a valid e-mail address.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form class="single-memberpressproduct postid-1945">
<input type="text" id="user_email1" value="" />
<input type="submit" class="mepr-submit" />
</form>

I ended up using different approach.
<script>
jQuery('.single-memberpressproduct.postid-1945 .mepr-submit').attr("disabled", "disabled");
var youtubeRegex = /edu/i;
jQuery('input#user_email1').keyup(function(){
jQuery(".single-memberpressproduct.postid-1945 .mepr-submit").attr("disabled", !youtubeRegex.test(this.value));
});
</script>

Related

How do I check if input is blank/not blank and do specific thing

Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.

javascript keyup to change divs not just text

I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>

How to make email id in a form optional in JavaScript

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">

Set custom HTML5 required field validation message

Required field custom validation
I have one form with many input fields. I have put html5 validations
<input type="text" name="topicName" id="topicName" required />
when I submit the form without filling this textbox it shows default message like
"Please fill out this field"
Can anyone please help me to edit this message?
I have a javascript code to edit it, but it's not working
$(document).ready(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter Room Topic Title");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
Email custom validations
I have following HTML form
<form id="myform">
<input id="email" name="email" type="email" />
<input type="submit" />
</form>
Validation messages I want like.
Required field: Please Enter Email Address
Wrong Email: 'testing#.com' is not a Valid Email Address. (here, entered email address displayed in textbox)
I have tried this.
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");
}
else {
input.setCustomValidity("");
}
}
This function is not working properly, Do you have any other way to do this? It would be appreciated.
Code snippet
Since this answer got very much attention, here is a nice configurable snippet I came up with:
/**
* #author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* #link https://stackoverflow.com/a/16069817/603003
* #license MIT 2013-2015 ComFreek
* #license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
Usage
→ jsFiddle
<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",
emptyText: "Please enter an email address!",
invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});
More details
defaultText is displayed initially
emptyText is displayed when the input is empty (was cleared)
invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)
You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.
Compatibility
Tested in:
Chrome Canary 47.0.2
IE 11
Microsoft Edge (using the up-to-date version as of 28/08/2015)
Firefox 40.0.3
Opera 31.0
Old answer
You can see the old revision here: https://stackoverflow.com/revisions/16069817/6
You can simply achieve this using oninvalid attribute,
checkout this demo code
<form>
<input type="email" pattern="[^#]*#[^#]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>
Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP
HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
function InvalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Required email address');
}
else if (textbox.validity.typeMismatch){{
textbox.setCustomValidity('please enter a valid email address');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/
Try this:
$(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("Please enter Room Topic Title");
};
}
})
I tested this in Chrome and FF and it worked in both browsers.
Man, I never have done that in HTML 5 but I'll try. Take a look on this fiddle.
I have used some jQuery, HTML5 native events and properties and a custom attribute on input tag(this may cause problem if you try to validade your code). I didn't tested in all browsers but I think it may work.
This is the field validation JavaScript code with jQuery:
$(document).ready(function()
{
$('input[required], input[required="required"]').each(function(i, e)
{
e.oninput = function(el)
{
el.target.setCustomValidity("");
if (el.target.type == "email")
{
if (el.target.validity.patternMismatch)
{
el.target.setCustomValidity("E-mail format invalid.");
if (el.target.validity.typeMismatch)
{
el.target.setCustomValidity("An e-mail address must be given.");
}
}
}
};
e.oninvalid = function(el)
{
el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
};
});
});
Nice. Here is the simple form html:
<form method="post" action="" id="validation">
<input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
<input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />
<input type="submit" value="Send it!" />
</form>
The attribute requiredmessage is the custom attribute I talked about. You can set your message for each required field there cause jQuery will get from it when it will display the error message. You don't have to set each field right on JavaScript, jQuery does it for you. That regex seems to be fine(at least it block your testing#.com! haha)
As you can see on fiddle, I make an extra validation of submit form event(this goes on document.ready too):
$("#validation").on("submit", function(e)
{
for (var i = 0; i < e.target.length; i++)
{
if (!e.target[i].validity.valid)
{
window.alert(e.target.attributes.requiredmessage.value);
e.target.focus();
return false;
}
}
});
I hope this works or helps you in anyway.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.
[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);
emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});
The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.
Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.
Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/
Hope that helps!
Just need to get the element and use the method setCustomValidity.
Example
var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
Use the attribute "title" in every input tag and write a message on it
you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!
Here is my demo codes!(you can run it to check out!)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oninvalid</title>
</head>
<body>
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
<input type="email" placeholder="xgqfrms#email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
<input type="submit" value="Submit">
</form>
</body>
</html>
reference link
http://caniuse.com/#feat=form-validation
https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation
You can add this script for showing your own message.
<script>
input = document.getElementById("topicName");
input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write
input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});
</script>
For other validation like pattern mismatch you can add addtional if else condition
like
else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}
there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid
use it on the onvalid attribute as follows
oninvalid="this.setCustomValidity('Special Characters are not allowed')

How to validate input using javascript

<script type="text/javascript">
function validate() {
if (document.form.price.value.trim() === "") {
alert("Please enter a price");
document.form.price.focus();
return false;
}
if (document.form.price.value !== "") {
if (! (/^\d*(?:\.\d{0,2})?$/.test(document.form.price.value))) {
alert("Please enter a valid price");
document.form.price.focus();
return false;
}
}
return true;
}
</script>
<form action="" method="post" name="form" id="form" onsubmit="return validate(this);">
<input name="price" type="text" class="r2" />
<input name="price2" type="text" class="r2" />
<input name="price3" type="text" class="r2" />
<input name="price4" type="text" class="r2" />
<input name="price5" type="text" class="r2" />
...more....
<input name="price50" type="text" class="r2" />
This javascript code is working fine to validate the field "price".
Question :
How to make the code to work as global validation? Example: would validate the price, price2, price3, price4, price5 etc.. with a single function. Please let me know :)
My personal recommendation would be something like this:
<script type="text/javascript">
function validate() {
return [
document.form.price,
document.form.price2,
document.form.price3,
document.form.price4,
document.form.price5
].every(validatePrice)
}
function validatePrice(price)
{
if (price.value.trim() === "") {
alert("Please enter a price");
price.focus();
return false;
}
if (price.value !== "") {
if (! (/^\d*(?:\.\d{0,2})?$/.test(price.value))) {
alert("Please enter a valid price");
price.focus();
return false;
}
}
return true;
}
</script>
If you do not plan on using jQuery this should work.
function validate() {
for (var field in document.getElementsByTagName('input')) {
if (isPriceField(field)) {
field.value = field.value.trim();
if (isNaN(parseFloat(field.value))) {
return alertAndFocus(field, "Please enter a valid price");
}
}
}
return true;
}
function isPriceField(field) {
return (field.name.substr(0, Math.min(5, field.name.length)) === 'price')
}
function alertAndFocus(field, message) {
alert(message);
field.focus();
return false;
}
$('#form input').each(function(){
console.log('valid',$(this)[0].validity.valid);
});
The easiest in this case is really to use jQuery. This way you can use a generic selector and apply the validation on all items.
$("#price*").each(function() {//Do your validation here $(this) is the item price, then price2 then price3})
For anything else you would need to query the DOM and then that doesn't work the same in all browsers.
Today, you can't really do anything in Javascript and ignore something like jQuery http://docs.jquery.com/ or Scriptalicious.
I use jsFormValidator to validate my form and it works like a charm. You don't need to add heavy syntax to your HTML tags, things like:
<input type="text" name="username" placeholder="Username" data-validate/>
You just create a basic JSON object to describe how you want to validate your form:
{
"email": {
"validEmail":true,
"required":true
},
"username": {
"minLength":5,
"maxLength":15
},
"password": {
"validPassword":true,
"match": "password",
"required":true
}
}
And then you just validate the whole form with on single line of code:
jsFormValidator.App.create().Validator.applyRules('Login'); //Magic!
You can validate all 5 prices and return true only if all 5 match your validation rules.
jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.
Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular form.
<form action="/registration" method="POST">
<p>
User name (4 characters minimum, only alphanumeric characters):
<input data-validation="length alphanumeric" data-validation-length="min4">
</p>
<p>
Year (yyyy-mm-dd):
<input data-validation="date" data-validation-format="yyyy-mm-dd">
</p>
<p>
Website:
<input data-validation="url">
</p>
<p>
<input type="submit">
</p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<script>
$.validate({
lang: 'es'
});
</script>

Categories

Resources