2012-01-24 20 views
11

Jestem naprawdę nowy dla mangusty, więc zastanawiałem się, czy jest jakiś sposób ustawienia custom error message zamiast domyślnego takiego jak Validator "required" failed for path password.Niestandardowy (przyjazny dla użytkownika) komunikat ValidatorError

Chciałbym ustawić coś w rodzaju Password is required., które jest bardziej przyjazne dla użytkownika.

Napisałem kilka niestandardowych sprawdzania poprawności i ustawiłem właściwość type za pomocą tego przyjaznego dla użytkownika komunikatu o błędzie, ale nie jestem pewien, czy type jest właściwym symbolem zastępczym dla komunikatu o błędzie. także nie ma sposobu, aby ustawić niestandardowy komunikat o predefiniowane walidatorami jak min, max, required, enum...

Jednym z rozwiązań jest, aby sprawdzić za każdym razem type własność błędu rzucony i ręcznie przypisać komunikat o błędzie, ale myślę, że to zadanie walidator za:

save model 
    if error 
     check error type (eg. "required") 
     assign fancy error message (eg. "Password is required.") 

ten oczywiście nie jest idealnym rozwiązaniem.

Spojrzałem na express-form i node-validator, ale nadal chcę użyć funkcji sprawdzania mangusty.

+0

Jest również wyrazić-walidator który działa dobrze. – chovy

Odpowiedz

16

Generalnie używam funkcji pomocnika dla takich rzeczy. Po prostu kpiłem z tego, żeby był trochę bardziej ogólny niż te, których używam. Ten gość weźmie wszystkie "domyślne" walidatory (wymagane, min., Maks., Itd.) I sprawi, że ich wiadomości będą trochę ładniejsze (zgodnie z obiektem messages) i wyodrębnią tylko wiadomość, którą przekazałeś w walidatorze dla niestandardowego zatwierdzenia.

function errorHelper(err, cb) { 
    //If it isn't a mongoose-validation error, just throw it. 
    if (err.name !== 'ValidationError') return cb(err); 
    var messages = { 
     'required': "%s is required.", 
     'min': "%s below minimum.", 
     'max': "%s above maximum.", 
     'enum': "%s not an allowed value." 
    }; 

    //A validationerror can contain more than one error. 
    var errors = []; 

    //Loop over the errors object of the Validation Error 
    Object.keys(err.errors).forEach(function (field) { 
     var eObj = err.errors[field]; 

     //If we don't have a message for `type`, just push the error through 
     if (!messages.hasOwnProperty(eObj.type)) errors.push(eObj.type); 

     //Otherwise, use util.format to format the message, and passing the path 
     else errors.push(require('util').format(messages[eObj.type], eObj.path)); 
    }); 

    return cb(errors); 
} 

i może być stosowany tak (wyrazić przykład router):

function (req, res, next) { 
    //generate `user` here 
    user.save(function (err) { 
     //If we have an error, call the helper, return, and pass it `next` 
     //to pass the "user-friendly" errors to 
     if (err) return errorHelper(err, next); 
    } 
} 

Przed:

{ message: 'Validation failed', 
    name: 'ValidationError', 
    errors: 
    { username: 
     { message: 'Validator "required" failed for path username', 
     name: 'ValidatorError', 
     path: 'username', 
     type: 'required' }, 
    state: 
     { message: 'Validator "enum" failed for path state', 
     name: 'ValidatorError', 
     path: 'state', 
     type: 'enum' }, 
    email: 
     { message: 'Validator "custom validator here" failed for path email', 
     name: 'ValidatorError', 
     path: 'email', 
     type: 'custom validator here' }, 
    age: 
     { message: 'Validator "min" failed for path age', 
     name: 'ValidatorError', 
     path: 'age', 
     type: 'min' } } } 

Po:

[ 'username is required.', 
    'state not an allowed value.', 
    'custom validator here', 
    'age below minimum.' ] 

Edycja: Snap, właśnie uświadomiłem sobie, że to było pytanie związane z CoffeeScript. Nie będąc facetem z CoffeeScript, nie chciałbym tego przepisywać w CS. Zawsze możesz po prostu wymagać tego jako pliku js w swoim CS?

+0

Dzięki człowieku :). Już rozwinąłem projekt mangusty i myślę, że to rozwiązałem. Wysyłam [prośbę o ściągnięcie] (https://github.com/LearnBoost/mongoose/pull/753) w celu mongozy. P.S. To wcale nie jest CoffeScript ... Chciałem napisać pseudo kod, ale moderator dodał tag CoffeScript :) – ManInTheBox

+0

Niesamowite dzięki człowieku – Unitech

0

Jeśli chcesz zdobyć pierwszy komunikat o błędzie, patrz poniższy przykład:

var firstError = err.errors[Object.keys(err.errors)[0]]; 
return res.status(500).send(firstError.message); 

Pozdrowienia, Nicholls

Powiązane problemy