I want to create a custom validation rule for the Aurelia Validator plugin. Essentially, I have a semicolon-delimited string of email addresses (in a To) field and I'd like to split this string and run email validations on each individual email address. I have the following so far (there are null check issues, but ignore that for now)
ValidationRules.customRule('multiEmail', (value, obj) => {
var emails = value.split(';');
emails.forEach(() => {
// Call the existing email validation functionality rule for each value?
});
});
Is this possible?
Related
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
I have a keycloak user with custom attributes like below.
I use Reactjs for front-end. I want to retrieve the custom attribute from the javascript side. Like this answer states.
https://stackoverflow.com/a/32890003/2940265
But I can't find how to do it on the javascript side.
I debugged in Chrome but I can't find a suitable result for custom attributes.
Please help
I found the answer.
I will post here, because someone may find it useful.
Well, You can add custom attributes to the user but you need extra configurations to retrieve it from the javascript side. For Beginner ease, I will write the answer from Adding customer to retrieving the attribute from javascript (in my case react js).
Let's add custom attributes to a user.
login into keycloak and choose your realm (if you have multiple realms unless you will automatically login to realm)
After that select Users -> View all users
Select your user in my case it's Alice
Select Attributes and add custom attributes (in my case I added custom attribute call companyId like below)
Now click Save
Now we have to Map Custom attribute with our keycloak client.
To front end to use keycloak you must have client in Clients (left side bar)
If you haven't you have to configure a client for that. In my case my client is test-app
Therefor select Clients -> test-app -> Mappers
Now we have to create Mapper. Click Create
For Token Claim Name you should give your custom attributes key (in my case it is companyId) for my ease, I use companyId for Name, Realm Role prefix, Token Claim Name. You should choose User Attribute in Mapper Type and String for Claim JSON Type
After that click Save. Now you can get your custom attribute from javascript.
let say your keycloak JavaScript object is keycloak, you can get companyId using keycloak.
let companyId = keyCloak.idTokenParsed.companyId;
sample code would be like below (my code in react.js)
keyCloak.init({
onLoad: 'login-required'
}).success(authenticated => {
if (authenticated) {
if (hasIn(keyCloak.tokenParsed, 'realm_access')) {
if (keyCloak.tokenParsed.realm_access.roles === []) {
console.log("Error: No roles found in token")
} else {
let companyId = keyCloak.idTokenParsed.companyId;
}
} else {
console.log("Error: Cannot parse token");
}
} else {
console.log("Error: Authentication failed");
}
}).error(e => {
console.log("Error: " + e);
console.log(keyCloak);
});
Hope somebody find this answer useful, because I could find an answer for JavaScript. Happy coding :)
The attributes can be retrieved via the user profile:
keycloak = ... // Keycloak instance
keycloak.loadUserProfile().success(function(profile) {
let companyId = profile.attributes.companyId[0];
alert('Company Id: ' + companyId);
}).error(function() {
alert('Failed to load user profile');
});
Each attribute is an array of strings. So unless you have several company IDs, the array will have a length of 1 and the relevant data is in element 0.
In addition to custom attrbutes, the following elements are available as part of the user profile:
id
username
email
firstName
lastName
enabled
emailVerified
totp
createdTimestamp
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.
Total novice here.
I'm trying to do a client side form validation for a subscribe to newsletter form. My client side code is such.
Template.body.events({
"submit .new-subscriber": function (event) {
// This function is called when the new task form is submitted
var newEmail = event.target.newEmail.value;
if (newEmail is email?){
Meteor.call("addNewSubscriber", newEmail);
}
I'm not sure how to perform form validation here? Can I perform the same server side?
We currently use two different approaches for email validation at Edthena depending on the situation. Hopefully one or both of these will fit your needs.
Regex
Regular expressions can be used for quick and dirty email validation. They will catch any obviously bogus emails like x#y.z or foo#bar, but that's about the limit of their accuracy. We use these inside the app on the client when an existing user has no motivation to enter an invalid address. Here's an example:
var isEmailValid = function(address) {
return /^[A-Z0-9'.1234z_%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(address);
};
In your case, you could add a call to isEmailValid in the submit handler. If the function returns false you could display an error instead of calling addNewSubscriber.
You can read more about email regular expressions here.
Mailgun
In cases where you think users could intentionally input invalid addresses, you can bring out the big guns and call the mailgun email validation API. This trades speed (results can take a couple of seconds to come back) for dramatically improved accuracy (mailgun does things like check that an MX record exists on the target domain). We use this approach in our public-facing forms.
Meteor.methods({
isEmailValid: function(address) {
check(address, String);
// modify this with your key
var result = HTTP.get('https://api.mailgun.net/v2/address/validate', {
auth: 'api:pubkey-XXXXXXXXXXXXX',
params: {address: address.trim()}
});
if (result.statusCode === 200) {
// is_valid is the boolean we are looking for
return result.data.is_valid;
} else {
// the api request failed (maybe the service is down)
// consider giving the user the benefit of the doubt and return true
return true;
}
}
});
In this example, isEmailValid is implemented as a method and can be called either on the server or the client depending on your needs. Note that you will need to get an API key and add the http package to your app with meteor add http.
For more details, see the docs.
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)
}
}