这可能是一个愚蠢的问题,但让我问一下。我希望将对象或代码片段作为字符串分配给变量,并在以后将其用作代码。
code_string = "rules:{hotel_name:{required: true, lettersonly: true}}";
var validator = $('#create_hotels').validate({
print code_string;
// How will I call code_string here to act as below ?
});
// want it working like this
var validator = $('#create_hotels').validate({
rules:{hotel_name:{required: true, lettersonly: true}},
});发布于 2019-07-18 19:37:27
只需很小的改动,您就可以将字符串解析为javascript对象。
更改是在字符串中包括{和},但也将字符串格式化为有效的json -包括"中的包装键。
var code_string = '{"rules":{"hotel_name":{"required": true, "lettersonly": true}}}';现在您可以使用JSON.parse了
var validator = $('#create_hotels').validate(JSON.parse(code_string));发布于 2019-07-18 19:44:33
code_string = '{"rules":{"hotel_name":{"required": true, "lettersonly": true}}}';
var validator = $('#create_hotels').validate({
print JSON.parse(code_string);
});在创建字符串时遵循json的语法...然后在需要的地方将其转换为json。
发布于 2019-07-18 19:39:05
简单,但对你来说应该很容易扩展。
像这样怎么样?
const isValid = {
name: str => str.length > 3,
age: int => {
const MIN_AGE = 18;
const MAX_AGE = 65;
if(isNaN(int)){
return false;
}
return age >= MIN_AGE && age <= MAX_AGE;
}
}
const john = { name: 'John', age: 21 };
const sarah = { name: '', age: 99 };
isValid['name'](john.name); // true
isValid['age'](john.age); // true
isValid['name'](sarah.name); // false
isValid['age'](sarah.age); // falsehttps://stackoverflow.com/questions/57093383
复制相似问题