问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/27680544/meteorjs-email-form-validation