Building Valdr custom validator - regex

I have been trying since to build a custom validator using Valdr AngularJs plugin with no success.
What I want to archive is an input text that should receive date and time format like : dd/MM/yyyy hh:mm (12/04/2015 12:32:10)
Based on Valdr documentation, this is what I have done so far :
myApp.factory('customValidator', function () {
return {
name: 'customValidator', // this is the validator name that can be referenced from the constraints JSON
validate: function (value, arguments) {
// value: the value to validate
// arguments: the validator arguments
return value === arguments.onlyValidValue;
}
};
});
myApp.config(function(valdrProvider)
{
valdrProvider.addValidator('customValidator');
valdrProvider.addConstraints(
{
'Person':
{
'date_send':
{
'customValidator':
{
'onlyValidValue':'^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$',
'message': 'Please date and time format has to be : 12/04/2015 12:32:10'
}
}
}
});
});
Then in my form, I have the following :
<input class="input" name="date_send" id="date_send" type="text" ng-model="date_send" />
But it doesn't work.
I will appreciate any help.
Thank you !

If you only need a regex validator, I'd recommend to use the one provided by valdr instead of writing a custom validator:
valdrProvider.addConstraints({
'Person': {
'date_send': {
'pattern': {
'value': '^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$',
'message': 'Please date and time format has to be : 12/04/2015 12:32:10'
}
}
}
});
If you want a custom validator, you have to implement the validation logic in the validator. You just copied the sample validator from the docs, which only compares the users input value with the 'onlyValidValue' configured in the constraints. What you want to do is more like:
valdrProvider.addConstraints({
'Person': {
'date_send': {
'customDateValidator': {
'message': 'Please date and time format has to be : 12/04/2015 12:32:10'
}
}
}
});
Custom validator:
myApp.factory('customDateValidator', function () {
return {
name: 'customDateValidator',
validate: function (value, arguments) {
var dateCheck = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$/
return dateCheck.test(value);
}
};
});

I can't be 100% sure because you didn't provide enough code but I guess your input field declaration should be
ng-model="person.date_send"
rather than
ng-model="date_send"
For reference please have a look at the custom validator demo. It's always helpful if you can provide a plunker with a complete sample.

Related

AdonisJS exists Validator

I'm following the official [documentation] (https://legacy.adonisjs.com/docs/4.0/validator) && indicative, but I couldn't find anything to help me.
I want to validate if the given param exists on database.
So I tried:
app/Validators/myValidator
const { rule } = use('Validator')
get rules () {
return {
userId: 'required|integer|exists:MyDatabase.users,userId', <-- this is what isn't working
date: [
rule('date'),
rule('dateFormat', 'YYYY-MM-DD')
]
}
}
// Getting the data to be validated
get data () {
const params = this.ctx.params
const { userId, date } = params
return Object.assign({}, { userId }, { date })
}
It gives me the following error:
{
"error": {
"message": "select * from `MyDatabase`.`users`.`userId` where `undefined` = '2' limit 1 - ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`userId` where `undefined` = '2' limit 1' at line 1",
"name": "ErrorValidator",
"status": 40
}
}
How should I properly indicate that I want to compare MyDatabase.users.userid to the given parameter?
After a few hard try/error I stumbled upon the solution.
Just need to follow what is inside hooks.js and pass the values separated by comma, like so:
get rules () {
return {
userId: 'required|integer|exists:MyDatabase,MyTable,columntoCompare',
}
}

How check name already exist using express validatator in update calls

I have to check the name is already exist in database before adding the values.
So, I have decided to add express validator custom option. This is working fine in create call. But not working in update call. Here is my code
const { check, body } = require('express-validator/check');
var models = require("../models");
let Validations = [
check('email').isEmail().withMessage("Invalid Email"),
check('phone').isLength({ min: 5 }).withMessage("Min length Required"),
check('name').not().isEmpty().withMessage("Value is Required"),
body("name").custom(value => {
return models.fundraisers.findByName(value).then(user => {
if (user) {
return Promise.reject('Name already in use');
}
})
})
]
How to handle this in update calls.
Thanks in advance.
This is my check and it worked well at create and update case :
check('name')
.not().isEmpty()
.isString()
.custom(value => {
return Group
.findByName(value)
.then(groups => {
if(groups.length > 0) {
return Promise.reject(value + '\'s already in use');
}
})
})
By the way, I defined only body-check :
const { check, validationResult } = require('express-validator/check');
Hope it helps :)

Ember CLI -- store.find doesn't work when searching for all results with a given name

I'm trying to search for all employees that have a title of developer
As per the documentation (http://guides.emberjs.com/v1.10.0/models/finding-records/) It seems the correct way to do this is:
return this.store.find('employee', { title: "developer" });
But this is not working in Ember CLI 0.2.2, and I can't even see my template when I try this, even though when I do
return this.store.find('employee')
I can see a list of all employees and there are multiple employees with that title
Turns out I needed to override the DS.FixtureAdapter::queryFixtures method. I went into my adapters/application.js file and added
queryFixtures: function(records, query, type) {
return records.filter(function(record) {
for(var key in query) {
if (!query.hasOwnProperty(key)) { continue; }
var value = query[key];
if (record[key] !== value) { return false; }
}
return true;
});
}

Mongoose validation: required : false, validate : regex, issues with empty values

I get this message from Mongoose validation:
'Validator failed for path phone with value ``'
That shouldn't happen since phone is not required.
Here's my model schema:
var user = new Schema(
{
_id : { type: String, required: true },
name : { type: String, required: true},
phone : { type: String, required: false, validate: /^\d{10}$/ },
password : { type: String },
added : { type: Date, default: Date.now },
},
{collection : 'users'}
);
It seems that mongoose's validation fails when i use required: false and set validate property up.
If I change it to:
phone : { type: String, required: false},
Everything goes right, why is that?
What am I doing wrong?
You can simply check if the value entered exists (not null or undefined). If it exists, then test the regex:
var user = new Schema(
{
_id : { type: String, required: true },
name : { type: String, required: true},
phone : { type: String,/*not required by default**/
validate: {
validator: function(v) {
var re = /^\d{10}$/;
return (!v || !v.trim().length) || re.test(v)
},
message: 'Provided phone number is invalid.'
}
},
password : { type: String },
added : { type: Date, default: Date.now },
},
{collection : 'users'}
);
I think your regex is failing validation on empty string which should in this case be valid since this field is not required. Why don't you try this regex:
/^$|^\d{10}$/
This will match an empty string or 10 digits.
You may try with a custom validator as they are only triggered when there is a value on a given key because the key selection for custom validation is done via path() :
var user = new Schema({
// ...
phone : { type: String }, // using default - required:false
// ...
});
// Custom validation
user.path('phone').validate(function (value) {
// Your validation code here, should return bool
}, 'Some error message');
Have a look at this question: Why Mongoose doesn't validate empty document?
This will also effectively prevent the document to be persisted to the DB if validation fails, unless you handle the error accordingly.
BonusTip: Try to approach custom validations in a simplistic way, for example try to avoid loops when possible and avoid using libraries like lodash or underscore for in my experience I've seen that these may have a significant performance cost when working with lots of transactions.
use this function:
const valid= (id) =>{
return id.match(/^[0-9a-fA-F]{24}$/) ? true : false;
}

Refresh a webpage just once after 5 seconds

I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?
try this:
setTimeout(function ()
{
if (self.name != '_refreshed_'){
self.name = '_refreshed_';
self.location.reload(true);
} else {
self.name = '';
}
}, 5000);
You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:
//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//check if our query string is already set:
if(getQuerystring(r) !== 1){
setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}
If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.
Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:
How to wait 5 seconds with jQuery?
$(document).ready(function() {
// Get data
$.ajax({
url : '/tommyStockExchange/Data',
dataType : 'html',
data : {
'format' : 'H',
'type' : 'E'
},
success : function(data) {
$("#executions").html(data);
},
statusCode : {
404 : function() {
alert('executions url 404 :(');
}
}
});
});
Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.
You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:
if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
setTimeout(function ()
{
var search = location.search;
location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
}, 5000);
}
Demo: http://jsbin.com/ofawuz/edit