Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Since vue-validator https://github.com/vuejs/vue-validator is being ready for Vuejs 2, what is the best way to implement frontend validation?
UPDATE
I've found this awesome plugin
Vee Validate
In my opinion, a good way to implement front end validation for VueJS is to use vuelidate.
It's very simple to use and powerful. It offers model-base validation, it means that it's what you define in data that is validated, so it's totally decoupled from the templates. It comes with common built-in validators for email , min and max length or required. And many others.
Since it's all ultimately Javascript, you could also use some of the existing Javascript validation libraries like Parsely.js or Validate.js to hook this up. One thing that's nice about the Validate.js library is that it's format could easily be stored in the global store if you're using Vuex:
var constraints = {
creditCardNumber: {
presence: true,
format: {
pattern: /^(34|37|4|5[1-5]).*$/,
message: function(value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^%{num} is not a valid credit card number", {
num: value
});
}
},
length: function(value, attributes, attributeName, options, constraints) {
if (value) {
// Amex
if ((/^(34|37).*$/).test(value)) return {is: 15};
// Visa, Mastercard
if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
}
// Unknown card, don't validate length
return false;
}
},
creditCardZip: function(value, attributes, attributeName, options, constraints) {
if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
return {
presence: {message: "is required when using AMEX"},
length: {is: 5}
};
}
};
Then used as such:
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}
validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}
validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined
validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}
You could also hook those validate() functions to your component with something along the lines of #blur=validate(...)
Currently there are not many choices. Take a look at vue-awesome where you can find the most relevant libraries. There are 2 at the moment.
If you are using semantic-ui or its an option for you they have an amazing form validation plugin.
semantic-ui-form-validation
I've used it with Vuejs and it works great.
I found this validator simple, flexible and well documented. It cover most scenarios of validating forms in Vue Js.
I used Jquery validator plugin in the past. Compared to that, this simple-vue-validator really stands out in its flexibility and its ability to validate both hard-coded and dynamically generated forms.
https://github.com/semisleep/simple-vue-validator
I used it extensively for my SaaS project and so far it has gone on really well.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
What is the best practice recommended pattern in Node/Javascript to avoid passing lots of arguments into a function?
function create(firstName, lastName, address, phoneNumber, username, password, dateOfBirth, age) {
...
}
Should it take in an object?
const input = {
firstName: 'John',
lastName: 'Doe',
...
};
function create(input) {
}
An object seems error prone since there is no validation on the number of properties it should contain and the key names.
An object seems error prone since there is no validation on the number
of properties it should contain and the keys.
I could pass in a function and an HTML element and nothing else into your first function; it would likely fail.
That, at its core, is a fundamental issue with any scripting language. The only way to know you messed up with a function is usually a runtime error. Once it's coded correctly, that's not so much of a concern.
Note that there are languages like TypeScript that are a great help to people that want to enforce this kind of correctness at "compile time".
Should it take in an object?
Node is almost exclusively used for web servers. In that context, your entry point is typical req.body, an object. Who the hell knows what's on that object? So you error handle at the front of server:
function bindUser(postBody, callback) {
var user = {};
if (!postBody.firstName) {
return callback(new Error("Missing firstName"));
}
user.firstName = postBody.firstName;
if (!postBody.lastName) {
return callback(new Error("Missing lastName"));
}
user.lastName = postBody.lastName;
if (!postBody.email) {
return callback(new Error("Missing email"));
}
user.email = postBody.email.toLowerCase();
callback(null, user);
}
Congrats, you've got a known object, and your future debugging has a consistent starting point. Now you build helper functions that do one specific task, e.g. combine a full name:
function combineName(firstName, lastName) {
return firstName + " " + lastName;
}
user.fullName = combineName(user.firstName, user.lastName);
Focus your error handling on places that aren't fully contained environments, i.e. I/O and external modules. Outside of that, keep your functions small and specific, and they won't need 10 arguments and a massive walls of guards. Your future debugging self will thank you.
So to specifically address the question:
What is the best practice recommended pattern in Node/Javascript to avoid passing lots of arguments into a function?
Design your application so that functions don't need 10 arguments.
If you do it like in your example, you can access the keys using Object.keys(input) then you can check the length or do additional validation. You can see if a property is at least 3 characters using something like:
var keys = Object.keys(input);
keys.every(function(key) {
return key.length > 3;
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying organize data types in React Flux-like application. All my data objects are immutable, for collections I am using immutable.js, which is perfect library for that. But for typed objects i use my own classes. I don't think it is the best solution, but i need to somehow handle default values, internal consistency, validations of data, add methods to that objects etc.
Is there some library available for that purpose?
Do you use immutable.js collections also for that kind of objects? So you handle consistency of data, validations and other functionality somewhere else?
Or do you use plain classes for that?
Do you think that is good idea to have typed objects in React/Flux based application?
Here is example of what kind of objects i mean and simple example how I use it.
class Event extends MyImmutableLib {
constructor(plain) {
this.start = plain.start;
this.end = plain.end;
this.name = plain.name || "unnamed event"; // some default value
this.attendants = plain.attendants || [];
this.valid = plain.start < plain.end; // simple check of validity, I can also throw exception if it is needed
Object.freeze(this); // I use freeze to be sure I don't accidentally change the object
}
getDuration() {
return this.end - plain.start; // methods are sometimes useful
}
addAttendant(newPerson) {
return this.set("attendants", this.attendants.concat([newPerson])) //immutable edit, so I return new object
}
}
var someEvent = new Event({start: new Date("2015-02-29"), end: new Date("2012-02-30")}) //
var jsMeetup = someEvent.set("name", "9th Js Meetup, Brno")
var jsMeetup = jsMeetup.addAttendant("Joe");
console.log(jsMeetup.name, jsMeetup.getDuration())
The best would be some library with:
Typed objects - so I would have my data better organized.
Default values
Validations
Methods
Immutability specific functions
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Create: function (title, text, orientation, trigger, layout) {
$(this).attr
},
The trigger parameter must receive one of two very specific words: 'hover' or 'click' and I can't think of a good way to ease the implementation of this function.
I did think of some solutions:
I can try to validate the parameter once already inside in the function and return a 'console.info' right after breaking the execution in case a wrong parameter has been sent, informing the developer of his mistake
I could create a ENUM and provide it as an interface for the developer (which would still make the developer have to read it in order to use it properly)
Occurred me while typing this post that I could just set standard values for the options, hence they're optional.
I just don't know which one is the best approach in a situation like this. Can I assume that the developer that is willing to use the code MUST read the code to find the best way to implement it or (as I suppose) I should be concerned with validations like the ones I described? Also which one is the best?
Comparing straight up with strings is a common practice in javascript. ENUM-like structures, although easy to implement, are usually not very used because you either have to define your ENUM-like as globals or do something like:
application.enums.myObject.hover= 1;
application.enums.myObject.click= 2;
myObject= new application.constructors.MyObject();
myObject.create(title, text, orientation, application.enums.myObject.hover, layout)
In this manner only application is global, but typing application.enums.myObject is a pain.
How to handle the error:
Option 1: throw an exception:
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
throw "error: invalid parameter trigger";
}
},
This will crash your script unless you have a catch clause somewhere. In some cases crashing the party is better than not providing a way to know what is wrong. If you intend on catching these exceptions (instead of letting them just crash the script) I recommed doing it properly by making classes for your errors and such.
Option 2: Return null.
Create: function (title, text, orientation, trigger, layout) {
if (trigger !== "hover" && trigger !== "click") {
return null;
}
},
This approach works better if you are going to use the return value of the function. When debugging you will see "object has no property named X" error when trying to use the return value (or your value will be coerced into the "null" string if you use it as such).
Option 3: Quietly ignore the error and do nothing. Either your script will crash on its own or it will do nothing. Not recommended
Observations:
1 - do not use the console object in production code. It's not part of the standard and IE does not expose it to the web page unless you open the developer console
2 - do not start your function names with an upper case letter unless it's a function that should be called with the 'new' keyword (ie a constructor function).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I'm writing single-page web application. Client interacts with server using AJAX retrieving quite complex JSON structures (generation of the values of some fields is more complex than others). Moreover different views display different portions of the data.
I would like retrieve from server only fields that are used by current view and merge retrieved structure with what I have on the client already.
For example complete structure I'm using is like this:
{ "A": "Value of A",
"B": { "X": "Value of B.X", "Y": "Value of B.Y" },
"C": { "L": 0, "N": 1, "M": 2 } }
And let's say, view #1 displays fields "A", "B"."X" and "C" and view #2 displays fields "A", "B"."Y" and "C". So if view 1 and 2 are consequently presented to a user I would like to retrieve "A", "B"."X" and "C" before showing the first view and then retrieve only "B"."Y" before showing the second view, because "A" and "C" were retrieve earlier (and we assume and values were not changed on the server).
Is the some Javascript library (framework) allowing to do this kind of merging? If not, how would you recommend to implement this functionality?
I don't think that any js framework implements this particular functionality, but you can do it with jquery. It has built in ajax methods (including getJSON) and it handles object merging quite well with the help from it's extend method.
The best way to resolve your problem is to implement the logic on the serverside : when you request the json object from the server, you send as parameters the fields that you already have and the server makes the decision of what fields it returns in the json.
In this case, a jquery implementation would be relative simple :
$(document).ready(function(){
var scriptUrl1 = 'your_server_side_script_path';
var scriptUrl2 = 'other_server_side_script_path';
var object;
$.getJson(scriptUrl1,function(result){
var keys = [];
$.each(result,function(i){keys.push(i);});
object = result;
$.getJson(scriptUrl2,{existingKeys : keys},function(result){
$.extend(object,result);
alert('your object is ready');
});
});
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
i want to make a bbs forum that using much Keyboard event ,
so which is the best Keyboard event library,
thanks
Just another to throw in the mix. I recently released one called Mousetrap. You can check out examples at http://craig.is/killing/mice
Try KeyboardJS
its as simple as
KeyboardJS.on('a', function(){ alert('hello!'); });
yet as flexible as
var bindInstance = KeyboardJS.on('ctrl + a, ctrl + b, c', function(event, keysPressedArray, keyComboString){
//you get the event object
console.log('event object', event);
//you get the keys pressed array
console.log('keys pressed', keysPressedArray);
//you get the key combo string
console.log('combo pressed', keyComboString);
console.log('I will fire when \'ctrl + a\' or \'ctrl +b\' or \'c\' is pressed down');
//block event bubble
return false;
}, function(event, keysPressedArray, keyComboString) {
console.log('I will fire on key up');
//block event bubble
return false;
});
you can clear a binding by calling
bindInstance.clear();
you can clear all binds with specific keys with
KeyboardJS.clear('a, b');
Its open source and available on Github. Its comes in ether a global library or an AMD module for RequireJS.
Here's an introduction video.
There, now stop worrying about the keyboard and code your app. ;)
KEYPRESS is focused on game input and supports any key as a modifier, among other features. It's also pre-packaged for Meteor.
From what I have seen Mousetrap is the only library that let's you specify key sequences rather than combinations. This came in very handy for my application.
Lots of JavaScript libraries come replete with ways of capturing key input and using it to your advantage. It's a good bet that you will be able to find a library to do just that, and nothing else. I don't have a lot of experience there, however.
I've been using Ext for a while now, and their KeyMap class is really easy to work with. Here is a simple example using it.
new Ext.KeyMap(Ext.getDoc(), {
key: 'abc',
alt: true,
handler: function(k, e) {
var t = Ext.getCmp('tabpanel');
switch(k) {
case 65:
t.setActiveTab(0);
break;
case 66:
t.setActiveTab(1);
break;
case 67:
t.setActiveTab(2);
break;
}
},
stopEvent: true
});
This takes class, Ext.TabPanel, and allows the user to push a keyboard key to change tabs, rather than clicking the tabs themselves.
It can, of course, do much more than this. This is a simple example of how it works though.
This one is pretty good for jquery.
https://github.com/jeresig/jquery.hotkeys
This one is better if you are starting and if you want to understand how hot-keys work.
https://github.com/UthaiahBollera/HotkeysInJavascriptLibrary
You can try this one...
http://unixpapa.com/js/key.html