How do I improve this email address validation method? - javascript

I have a form called sub_form with 2 inputs, one of the inputs is an email address, the other is a choice from a dropdown menu. The Javascript below checks if the email address is valid, and also prints the values of both the inputs to the console log.
The problem is, when an incorrect email is entered, it shows the error message but still prints to the console.
How can I fix this so that the inputs only print to console if a valid email is entered?
<!-- validator -->
$('#sub_form').bootstrapValidator({live: 'disabled',
fields: {
email: {
validators: {
emailAddress: {
message: 'Invalid email' } }},}});
<!--print to console-->
document.getElementById('sub_form').onsubmit = function(){
console.log(document.getElementById('email').value);
console.log(document.getElementById('dropdown').value);
return false;
}

Per my comment on the question, this validation library as far as I've been able to tell is an older version of the one here. My company happens to use the same one, so I've been using that site a lot for reference. Just replace mentions of the "formValidation" method with "bootstrapValidator", and events use the "bv" namespace instead of "fv".
The validator should provide some methods for checking its valid state. You could use:
var validator = $('#sub_form').data('bootstrapValidator');
if (validator.isValidField('email')) {
console.log(document.getElementById('email').value);
}
See here for more info.

Related

express-validator: Handling conditional validation

I have a form which takes the user email and password. I have setup validation with express validator which checks if the user email and password are empty and if email is a valid email as shown below.
const loginSchema = [
body("email")
.isEmail()
.withMessage("email must contain a valid email address")
.notEmpty()
.withMessage("please enter email"),
body("password").notEmpty().withMessage("please enter password"),
];
When testing in postman, if a user was to submit the form without entering email and password, it displays all error messages. How do I use conditionals with express validator to make it so that isEmail() withMessage is only called if the request body email is not empty?
From express-validator docs:
If the option onlyFirstError is set to true, then only the first error for each field will be included.
So you basically have to do this instead
validationResult(req).array({ onlyFirstError: true })
Alternatively, you can use the following to have the errors from a request be a map from field path to first error of that field:
validationResult(req).mapped()

HTML5 constraint validation for custom check

I would like to check if username and email address is unique on client side.
Is there any way to add custom validation for constraint validation?
Or is there any other recommended way for this?
I assume I have to send async http request (I am using node js on server side) but would like to follow best practice for this one.
Yes you can use the setCustomValidity function from the constraint validation api, which is part of every form field (e.g., HTMLInputElement).
<input name="username">
<script>
const field = document.querySelector('[name="username"]');
field.addEventListener('change', () => {
fetch('https://example.com/myapiforcheckingusername' {
method:'POST',
body: JSON.stringify({username: field.value})
}).then((response) => {
const alreadyExists = // process response to check if username already exists
if (alreadyExists) {
field.setCustomValidity('The username already exists!');
}
});
});
</script>
The above code shows how to make an async validation on an input field. If the setCustomValidity is not the empty string it means it is a form error. If checkValidity is called on the accompanying form it returns false then.
You can check the MDN documentation for further examples on this matter.
you can make a request on input's blur to check if what user has written in input is unique or not and show result to user with check mark or red X
or you can show user after he clicked on signup button but i prefer the first solution

JQuery Validation Plugin Remote Validation Error always fires [duplicate]

This question already has answers here:
jQuery Validate remote method usage to check if username already exists
(2 answers)
Closed 8 years ago.
On my home page I have a log in modal that asks for the users email address and password through a basic form. When the email address is entered I have a remote validation that checks to see if the email address is in my blacklisted table in my DB. But the remote error fires off no matter if the PHP returns false or true and will not let the form submit, even if the PHP returns true. All of the validation works correct except for the remote. I can not seem to fix this problem and I have looked all over and nothing I find can solve this problem.
Home jQuery
$(function(){
$("#frmSignIn").validate({
rules: {
InputEmailAddress: {
required: true,
email: true,
remote:"scripts/blacklist.php"
},
InputPassword: {
required: true,
minlength: 3,
maxlength: 20
}
},
messages: {
InputEmailAddress:{
required:"Don't forget your email address!",
email:"Please enter a valid email address",
remote:"This email address has been backlisted"
},
InputPassword:{
required:"Please enter your password",
minlength:"Password must be longer than 3 characters",
maxlength:"Password can not be longet than 20 characters"
}
},
submitHandler: function(){
var data = $("#frmSignIn").serialize();
$.post('posted.php', data, function(o){
console.log(o);
},'json');
}
});
});
PHP
I will add the actual table check after I get this working
$email = $_GET['InputEmailAddress'];
$valid = true;
echo json_encode($valid);
The problem was that remote:'scripts/blacklist.php' was in single ''
Soon as I changed it to double quotes "scripts/blacklist.php" it works fine...
If anyone knows why I would love to know so I can understand, but problem solved!

backbone validate single attribute in save only

I have one model with 2 attributes. Let me explain first.
Backbone.Model.extend({
validation: {
username: [
{required: true, msg: 'Enter email/username.'},
],
password: [
{required: true,msg: 'Enter password.'},
{minLength:20,msg: 'Incorrect password length.'}]
},
});
I want validate single attribute in save function. Do you have any idea?
means, If my username & password field is blank, then error should be occurred for username only.
I am using backbone.validation with backbone.
Thanks
To validate a single or multiple properties, using Backbone.Validation, use the following code:
yourModel.isValid('username') // or
yourModel.isValid([ 'attribute1', 'attribute2' ])
There are two approaches you might use:
Approach 1
I think the easiest way to do this would be that you don't set the password field until after the username is validated. To quote from the FAQ:
What gets validated when?
If you are using Backbone v0.9.1 or later, all attributes in a model will be validated. However, if for instance name never has been set (either explicitly or with a default value) that attribute will not be validated before it gets set.
This is very useful when validating forms as they are populated, since you don't want to alert the user about errors in input not yet entered.
If you need to validate entire model (both attributes that has been set or not) you can call validate() or isValid(true) on the model.
So, don't call validate on your whole model. Call it on the username field first, then the password field.
Also, don't set the password field in your model until after the username has been validated.
Approach 2
Another approach would be to use the conditional validation described in the FAQ:
Do you support conditional validation?
Yes, well, sort of. You can have conditional validation by specifying the required validator as a function.
So, your code might look something like:
Backbone.Model.extend({
validation: {
username: [
{required: true, msg: 'Enter email/username.'},
],
password: [
{required: function(val, attr, username) {
return Bool(username); //some code here- return true if username is set, false if it is not. This rough example may not work in the real world.
},msg: 'Enter password.'},
{minLength:20,msg: 'Incorrect password length.'}]
},
});
I'm pretty sure that's what Ulugbek Komilovich is suggesting, though I'm not sure the syntax in that answer is quite correct.
M = Backbone.Model.extend({
validation: {
username: [
{required: true, msg: 'Enter email/username.'},
],
password: function(value, attr, computedState) {
// new M(this.get('username')); //or use second way
if(this.get('username')) {
return 'Enter email/username.';
}
// other checks
}
},
});

Checking if an email is valid in Google Apps Script

I'm using the built-in api for scripting against Google Spreadsheets to send some booking confirmations, and currently my script breaks if someone has filled in an invalid email. I'd like it to just save some data to a list of guests that haven't been notified, and then proceed with looping through the bookings.
This is my current code (simplified):
// The variables email, subject and msg are populated.
// I've tested that using Browser.msgBox(), and the correct column values are
// found and used
// The script breaks here, if an incorrect email address has been filled in
MailApp.sendEmail(email, subject, msg)
According to the documentation the only two methods on the MailApp class are to send emails and check the daily quota - nothing about checking for valid email addresses - so I don't really know what criteria must be fulfilled for the class to accept the request, and thus can't write a validation routine.
If you need to validate email addresses beforehand, create a blank spreadsheet in your drive. Then, run the function below, changing the testSheet variable to point to the spreadsheet you created. The function will do a simple regex test to catch malformed addresses, then check if the address is actually valid by attempting to temporarily add it as a viewer on the spreadsheet. If the address can be added, it must be valid.
function validateEmail(email) {
var re = /\S+#\S+\.\S+/;
if (!re.test(email)) {
return false;
} else {
var testSheet = SpreadsheetApp.openById(arbitrarySpreadsheetInYourDrive);
try {
testSheet.addViewer(email);
} catch(e) {
return false;
}
testSheet.removeViewer(email);
return true;
}
}
regex from How to validate email address in JavaScript?
Stay calm, catch and log the exception and carry on:
try {
// do stuff, including send email
MailApp.sendEmail(email, subject, msg)
} catch(e) {
Logger.log("Error with email (" + email + "). " + e);
}
On the otherhand, avoid Checking email in script and get rid of loses quota or try-catch etc. I used that I got a valid email when user attempt to send an email, by signing him in an email and got that email:
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String s = account.getEmail(); // here is the valid email.
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
}
Full procedure Here.
This answer is much later than this question was asked, but I piggy-backed off of remitnotpaucity's answer based on a comment in his answer. It does basically the same thing, adding the email to the spreadsheet and catching the error, however in my case it creates a new spreadsheet, attempts to add the user, and then after attempting to add the user, deletes the spreadsheet. In both cases, that the email is a valid email or not, it deletes the newly created spreadsheet.
Some things to note:
I am not as familiar with regular expressions, so I only check to see if the # symbol is within the email read into the function, and do not check for whitespaces.
I believe that even if it passes the first if-statement, even if it's not a valid email, an error will still be thrown and caught because Google will still catch that it's not a valid email, making the first if-statement redundant
If you are trying to validate an email outside your company, I'm unsure how it would react, so be fore-warned about that
This validation method takes a few seconds because you are creating and then deleting an email all within a single function, so it takes a fair bit longer than remitnotpaucity's
Most importantly, if you are able to, I would use an API. I believe that this one would work perfectly fine and should be free, it just may take some extra elbow-grease to get to work with GAS.
function validateEmail(email){
let ss = SpreadsheetApp.openByUrl(SpreadsheetApp.create('Email Validation Spreadsheet', 1, 1).getUrl())
if(!new RegExp('[#]').test(email)){
return false
} else{
try{
ss.addViewer(email)
} catch(e){
setTrashed()
return false
}
setTrashed()
return true
}
function setTrashed(){
DriveApp.getFilesByName('Email Validation Spreadsheet').next().setTrashed(true)
}
}

Categories